根据网络连接(文件链接)下载文件到本地
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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 提示词工程——AI应用必不可少的技术
· 地球OL攻略 —— 某应届生求职总结
· 字符编码:从基础到乱码解决
· SpringCloud带你走进微服务的世界