using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
namespace ConsoleTest
{
class HttpDldFile
{
/// <summary>
/// Http方式下載文件
/// </summary>
/// <param name="url">http地址</param>
/// <param name="localfile">本地文件</param>
/// <returns></returns>
public bool httpDownload(string url,string localfile)
{
bool flag = false;
long startPosition = 0; // 上次下載的文件起始位置
FileStream writeStream; // 寫入本地文件流對象
// 判斷要下載的文件夾是否存在
if (File.Exists(localfile))
{
writeStream = File.OpenWrite(localfile); // 存在則打開要下載的文件
startPosition = writeStream.Length; // 獲取已經(jīng)下載的長度
writeStream.Seek(startPosition, SeekOrigin.Current); // 本地文件寫入位置定位
}
else
{
writeStream = new FileStream(localfile, FileMode.Create);// 文件不保存創(chuàng)建一個(gè)文件
startPosition = 0;
}
try
{
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);// 打開網(wǎng)絡(luò)連接
if (startPosition > 0)
{
myRequest.AddRange((int)startPosition);// 設(shè)置Range值,與上面的writeStream.Seek用意相同,是為了定義遠(yuǎn)程文件讀取位置
}
Stream readStream = myRequest.GetResponse().GetResponseStream();// 向服務(wù)器請求,獲得服務(wù)器的回應(yīng)數(shù)據(jù)流
byte[] btArray = new byte[512];// 定義一個(gè)字節(jié)數(shù)據(jù),用來向readStream讀取內(nèi)容和向writeStream寫入內(nèi)容
int contentSize = readStream.Read(btArray, 0, btArray.Length);// 向遠(yuǎn)程文件讀第一次
while (contentSize > 0)// 如果讀取長度大于零則繼續(xù)讀
{
writeStream.Write(btArray, 0, contentSize);// 寫入本地文件
contentSize = readStream.Read(btArray, 0, btArray.Length);// 繼續(xù)向遠(yuǎn)程文件讀取
}
//關(guān)閉流
writeStream.Close();
readStream.Close();
flag = true; //返回true下載成功
}
catch (Exception)
{
writeStream.Close();
flag = false; //返回false下載失敗
}
return flag;
}
}
}
測試代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
HttpDldFile df = new HttpDldFile();
df.httpDownload("http://files.cnblogs.com/files/xiandedanteng/Convertor20170624.zip","C:\\123\\Convertor20170624.zip");
}
}
}