首页 > 代码库 > C# Http文件下载公共类(支持断点续传)

C# Http文件下载公共类(支持断点续传)

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.IO; 6 using System.Net; 7  8 namespace XcDownLoadFile 9 {10     public class DownLoadFile11     {12         ///13         /// 下载文件方法14         ///15         /// 文件保存路径和文件名16         /// 返回服务器文件名17         ///18         public bool DeownloadFile(string strFileName, string file)19         {20             bool flag = false;21             //打开上次下载的文件22             long SPosition = 0;23             //实例化流对象24             FileStream FStream;25             //判断要下载的文件夹是否存在26             if (File.Exists(strFileName))27             {28                 //打开要下载的文件29                 FStream = File.OpenWrite(strFileName);30                 //获取已经下载的长度31                 SPosition = FStream.Length;32                 FStream.Seek(SPosition, SeekOrigin.Current);33             }34             else35             {36                 //文件不保存创建一个文件37                 FStream = new FileStream(strFileName, FileMode.Create);38                 SPosition = 0;39             }40             try41             {42                 //打开网络连接43                 HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create("http://www.newxing.com/download/" + file);44                 if (SPosition > 0)45                     myRequest.AddRange((int)SPosition);             //设置Range值46                 //向服务器请求,获得服务器的回应数据流47                 Stream myStream = myRequest.GetResponse().GetResponseStream();48                 //定义一个字节数据49                 byte[] btContent = new byte[512];50                 int intSize = 0;51                 intSize = myStream.Read(btContent, 0, 512);52                 while (intSize > 0)53                 {54                     FStream.Write(btContent, 0, intSize);55                     intSize = myStream.Read(btContent, 0, 512);56                 }57                 //关闭流58                 FStream.Close();59                 myStream.Close();60                 flag = true;        //返回true下载成功61             }62             catch (Exception)63             {64                 FStream.Close();65                 flag = false;       //返回false下载失败66             }67             return flag;68         }69     }70 }
View Code

感谢:http://www.cnblogs.com/skyay/p/3880221.html

C# Http文件下载公共类(支持断点续传)