C#文件下载(实现断点续传)
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
1 public class WebDown
2 { 4 /// 下载文件方法 6 /// 文件保存路径和文件名 7 /// 返回服务器文件名 9 public static bool DeownloadFile(string sourceFile, string desFile) 10 { 11 bool flag = false; 12 long SPosition = 0; 13 FileStream FStream = null; 14 Stream myStream = null; 15 string fileName = sourceFile.Substring(sourceFile.LastIndexOf(@"/") + 1); 16 if (desFile.EndsWith("\\")) 17 { 18 desFile = desFile + fileName; 19 } 20 else 21 { 22 desFile = desFile + "\\" + fileName; 23 } 24 try 25 { 26 //判断要下载的文件夹是否存在 27 if (File.Exists(desFile)) 28 { 29 //打开上次下载的文件 30 FStream = File.OpenWrite(desFile); 31 //获取已经下载的长度 32 SPosition = FStream.Length; 33 long serverFileLength = GetHttpLength(sourceFile); 34 if (SPosition == serverFileLength) 35 {//文件是完整的,直接结束下载任务 36 return true; 37 } 38 FStream.Seek(SPosition, SeekOrigin.Current); 39 } 40 else 41 { 42 //文件不保存创建一个文件 43 FStream = new FileStream(desFile, FileMode.Create); 44 SPosition = 0; 45 } 46 //打开网络连接 47 HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(sourceFile); 48 if (SPosition > 0) 49 { 50 myRequest.AddRange(SPosition); //设置Range值 51 } 52 //向服务器请求,获得服务器的回应数据流 53 myStream = myRequest.GetResponse().GetResponseStream(); 54 //定义一个字节数据 55 byte[] btContent = new byte[512]; 56 int intSize = 0; 57 intSize = myStream.Read(btContent, 0, 512); 58 while (intSize > 0) 59 { 60 FStream.Write(btContent, 0, intSize); 61 intSize = myStream.Read(btContent, 0, 512); 62 } 63 flag = true; //返回true下载成功 64 } 65 catch (Exception ex) 66 { 67 SysLog.WriteTxtLog("下载文件时异常:" + ex.Message); 68 } 69 finally 70 { 71 //关闭流 72 if (myStream != null) 73 { 74 myStream.Close(); 75 myStream.Dispose(); 76 } 77 if (FStream != null) 78 { 79 FStream.Close(); 80 FStream.Dispose(); 81 } 82 } 83 return flag; 84 } 85 static long GetHttpLength(string url) 86 { 87 long length = 0; 88 try 89 { 90 var req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url)); 91 req.Method = "HEAD"; 92 req.Timeout = 5000; 93 var res = (HttpWebResponse)req.GetResponse(); 94 if (res.StatusCode == HttpStatusCode.OK) 95 { 96 length = res.ContentLength; 97 } 98 res.Close(); 99 return length; 100 } 101 catch (WebException wex) 102 { 103 return 0; 104 } 105 } 106 } 该文章在 2021/1/29 21:58:11 编辑过 |
关键字查询
相关文章
正在查询... |