C#文件下載(實(shí)現(xiàn)斷點(diǎn)續(xù)傳)
當(dāng)前位置:點(diǎn)晴教程→知識管理交流
→『 技術(shù)文檔交流 』
1 public class WebDown
2 { 4 /// 下載文件方法 6 /// 文件保存路徑和文件名 7 /// 返回服務(wù)器文件名 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 //獲取已經(jīng)下載的長度 32 SPosition = FStream.Length; 33 long serverFileLength = GetHttpLength(sourceFile); 34 if (SPosition == serverFileLength) 35 {//文件是完整的,直接結(jié)束下載任務(wù) 36 return true; 37 } 38 FStream.Seek(SPosition, SeekOrigin.Current); 39 } 40 else 41 { 42 //文件不保存創(chuàng)建一個文件 43 FStream = new FileStream(desFile, FileMode.Create); 44 SPosition = 0; 45 } 46 //打開網(wǎng)絡(luò)連接 47 HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(sourceFile); 48 if (SPosition > 0) 49 { 50 myRequest.AddRange(SPosition); //設(shè)置Range值 51 } 52 //向服務(wù)器請求,獲得服務(wù)器的回應(yīng)數(shù)據(jù)流 53 myStream = myRequest.GetResponse().GetResponseStream(); 54 //定義一個字節(jié)數(shù)據(jù) 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 //關(guān)閉流 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 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |