【C#】asp.net之HTTP協(xié)議斷點續(xù)傳
當前位置:點晴教程→知識管理交流
→『 技術文檔交流 』
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; namespace HttpDemo { class Program { //需要下載的路徑 static string url = "http://www.aseoe.com/demo/api/jquery_aseoe_001.zip"; //獲取文件全稱 static string fileName = Path.GetFileName(url); //保存路徑 static string localPath = "D:\\HttpCeShi\\" + fileName; //未下載完后面加.temp后綴名 static string tempPath = localPath + ".temp"; //偏移量(斷點) static int pos; static void Main(string[] args) { DownLoad(); Console.ReadLine(); } public static void DownLoad() { //如果存在要更新的文件就結束 if (File.Exists(localPath)) return; Stream localfs = null; //如果不存在未上傳完文件(需斷點續(xù)傳文件) if (File.Exists(tempPath)) { localfs = new FileStream(tempPath, FileMode.Open); } else { localfs = new FileStream(tempPath, FileMode.Create); } //獲取斷點 pos = (int)localfs.Length; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Headers.Add("Accept-Charset", "GBK,utf-8"); request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"; request.Method = "GET"; request.Timeout = 30000; //文件總長度單位(B) long total = request.GetResponse().ContentLength; Console.WriteLine("總長度為:" + total); if (pos > 0) request.AddRange(pos);//偏移到斷點 HttpWebResponse responseResult = (HttpWebResponse)request.GetResponse(); using (Stream stream = responseResult.GetResponseStream()) { byte[] buffer = new byte[total - pos]; int readSize = stream.Read(buffer, 0, buffer.Length); while (readSize > 0) { localfs.Write(buffer, 0, readSize); readSize = stream.Read(buffer, 0, buffer.Length); Console.WriteLine("已下載:" + localfs.Length); } localfs.Close(); File.Move(tempPath, localPath);//將臨時文件改為正常文件后綴 Console.WriteLine("下載完成!!!"); } } } }
該文章在 2021/3/3 17:39:36 編輯過 |
關鍵字查詢
相關文章
正在查詢... |