下载远程文件
1 public static bool DownRemoteFile(string url, string filepath) 2 { 3 ServicePointManager.DefaultConnectionLimit = 200; 4 try 5 { 6 //对远程文件发送一个请求 7 HttpWebRequest webReq = HttpWebRequest.CreateHttp(url); 8 webReq.ServicePoint.Expect100Continue = false; 9 webReq.ServicePoint.UseNagleAlgorithm = false; 10 webReq.ServicePoint.ConnectionLimit = 65500; 11 webReq.AllowWriteStreamBuffering = false; webReq.Proxy = null; 12 13 //接收远程WEB服务器发回的响应 14 WebResponse webRes = webReq.GetResponse(); 15 16 17 18 MemoryStream ms = new MemoryStream(); 19 webRes.GetResponseStream().CopyTo(ms); 20 //获取文件长度 21 long fileLength = webRes.ContentLength; 22 byte[] bufferbyte = ms.ToArray(); 23 24 25 //判断存储路径每一个节点是否存在 26 if (!System.IO.File.Exists(filepath)) 27 { 28 string[] dirArray = filepath.Split('\\'); 29 string temp = string.Empty; 30 for (int i = 0; i < dirArray.Length - 1; i++) 31 { 32 temp += dirArray[i].Trim() + "\\"; 33 if (!Directory.Exists(temp)) 34 Directory.CreateDirectory(temp); 35 } 36 } 37 //创建一个文件流,将处理的文件流写入磁盘 38 FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite); 39 fs.Write(bufferbyte, 0, bufferbyte.Length); 40 ms.Close(); 41 fs.Close(); 42 43 if (!System.IO.File.Exists(filepath)) 44 { 45 return false; 46 } 47 else 48 { 49 return true; 50 } 51 } 52 catch (Exception ex) 53 {
55 return false; 56 } 57 }