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; // 獲取已經下載的長度
writeStream.Seek(startPosition, SeekOrigin.Current); // 本地文件寫入位置定位
}
else
{
writeStream = new FileStream(localfile, FileMode.Create);// 文件不保存創建一個文件
startPosition = 0;
}
try
{
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);// 打開網絡連接
if (startPosition > 0)
{
myRequest.AddRange((int)startPosition);// 設置Range值,與上面的writeStream.Seek用意相同,是為了定義遠程文件讀取位置
}
Stream readStream = myRequest.GetResponse().GetResponseStream();// 向服務器請求,獲得服務器的回應數據流
byte[] btArray = new byte[512];// 定義一個字節數據,用來向readStream讀取內容和向writeStream寫入內容
int contentSize = readStream.Read(btArray, 0, btArray.Length);// 向遠程文件讀第一次
while (contentSize > 0)// 如果讀取長度大于零則繼續讀
{
writeStream.Write(btArray, 0, contentSize);// 寫入本地文件
contentSize = readStream.Read(btArray, 0, btArray.Length);// 繼續向遠程文件讀取
}
//關閉流
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");
}
}
}