![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 DownLoadFile 11 { 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 else 35 { 36 //文件不保存创建一个文件 37 FStream = new FileStream(strFileName, FileMode.Create); 38 SPosition = 0; 39 } 40 try 41 { 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 }