本文共 1744 字,大约阅读时间需要 5 分钟。
一、简单下载方式使用WebClient
////// 简单下载方式/// 说明:对于大文件的下载,当前处理,会出现假死,长时间之后如果现在成功才相应/// 不能用户断点处理/// public static void Test1(){ //string url = "http://www.imooc.com/video/11555"; string url = "http://v2.mukewang.com/98672526-02b5-454c-b31e-d8526755b40b/L.mp4?auth_key=1474171330-0-0-8ff3fe3a33cfd257577dfa999e41530d"; DateTime start = DateTime.Now; Uri uri = new Uri(url); string filename = uri.AbsolutePath.Substring(uri.AbsolutePath.LastIndexOf("/") + 1); filename = LocalPathHelper.CurrentSolution + "/data/" + filename; //指定url 下载文件 WebClient client = new WebClient(); client.DownloadFile(url, filename); Console.WriteLine("下载文件成功,用时:" + (DateTime.Now - start).TotalSeconds + "秒");}
二、分块下载
////// 分段下载文件/// 读取速度和分块大小、网速有关/// public static void Test3(){ string url = "http://v2.mukewang.com/98672526-02b5-454c-b31e-d8526755b40b/L.mp4?auth_key=1474171330-0-0-8ff3fe3a33cfd257577dfa999e41530d"; DateTime start = DateTime.Now; Uri uri = new Uri(url); string filename = uri.AbsolutePath.Substring(uri.AbsolutePath.LastIndexOf("/") + 1); filename = LocalPathHelper.CurrentSolution + "/data/" + filename; //指定url 下载文件 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); Stream stream = request.GetResponse().GetResponseStream(); //创建写入流 FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write); byte[] bytes = new byte[1024 * 512]; int readCount = 0; while (true) { readCount = stream.Read(bytes, 0, bytes.Length); if (readCount <= 0) break; fs.Write(bytes, 0, readCount); fs.Flush(); } fs.Close(); stream.Close(); Console.WriteLine("下载文件成功,用时:" + (DateTime.Now - start).TotalSeconds + "秒");}
更多:
转载地址:http://nfogi.baihongyu.com/