根据网络连接(文件链接)下载文件到本地

复制代码
 1   public void DownloadFile(string URL, string filename)
 2   {
 3       HttpWebRequest req = null;
 4       HttpWebResponse rep = null;
 5       Stream st = null;
 6       Stream so = null;
 7       try
 8       {
 9           req = (HttpWebRequest)WebRequest.Create(URL);//请求网络资源
10 
11           req.UserAgent = "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Mobile Safari/537.36";
12 
13           rep = (HttpWebResponse)req.GetResponse();//返回Internet资源的响应
14           long totalBytes = rep.ContentLength;//获取请求返回内容的长度
15           st = rep.GetResponseStream();//读取服务器的响应资源,以IO流的形式进行读写
16           so = new FileStream(filename, FileMode.Create);
17           long totalDownloadedByte = 0;
18           byte[] by = new byte[1024];
19           int osize = st.Read(by, 0, (int)by.Length);
20           while (osize > 0)
21           {
22               totalDownloadedByte = osize + totalDownloadedByte;
23               so.Write(by, 0, osize);
24               osize = st.Read(by, 0, (int)by.Length);//读取当前字节流的总长度
25           }
26           so.Flush();
27       }
28       catch (Exception ex) { ex.ToString(); }
29       finally
30       {
31           if (so != null) { so.Close(); so.Dispose(); }
32           if (st != null) { st.Close(); st.Dispose(); }
33           if (rep != null) { rep.Close(); rep.Dispose(); }
34           if (req != null) { req.Abort(); }
35 
36       }
37   }
复制代码

 

posted @   Chanwah  阅读(49)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 提示词工程——AI应用必不可少的技术
· 地球OL攻略 —— 某应届生求职总结
· 字符编码:从基础到乱码解决
· SpringCloud带你走进微服务的世界
点击右上角即可分享
微信分享提示