C#客户端直接从服务器下载文件到本地
1、局域网文件下载:
1 public class RemoteDownload 2 { 3 public static void DownLoad(string addressUrl,string localName) 4 { 5 //下载文件 6 System.Net.WebClient myWebClient = new System.Net.WebClient(); 7 myWebClient.DownloadFile(@"/10.2.0.254/software/01279.lic.txt", "testdownload.txt"); 8 //下载end 9 } 10 }
2、通过web方式,从远程服务器端下载文件:
1 public class WebDownload 2 { 3 public static void DownLoad(string Url, string FileName) 4 { 5 bool Value = false; 6 WebResponse response = null; 7 Stream stream = null; 8 9 try 10 { 11 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); 12 13 response = request.GetResponse(); 14 stream = response.GetResponseStream(); 15 16 if (!response.ContentType.ToLower().StartsWith("text/")) 17 { 18 Value = SaveBinaryFile(response, FileName); 19 20 } 21 22 } 23 catch (Exception err) 24 { 25 string aa = err.ToString(); 26 } 27 28 } 29 30 /// <summary> 31 /// Save a binary file to disk. 32 /// </summary> 33 /// <param name="response">The response used to save the file</param> 34 // 将二进制文件保存到磁盘 35 private static bool SaveBinaryFile(WebResponse response, string FileName) 36 { 37 bool Value = true; 38 byte[] buffer = new byte[1024]; 39 40 try 41 { 42 if (File.Exists(FileName)) 43 File.Delete(FileName); 44 Stream outStream = System.IO.File.Create(FileName); 45 Stream inStream = response.GetResponseStream(); 46 47 int l; 48 do 49 { 50 l = inStream.Read(buffer, 0, buffer.Length); 51 if (l > 0) 52 outStream.Write(buffer, 0, l); 53 } 54 while (l > 0); 55 56 outStream.Close(); 57 inStream.Close(); 58 } 59 catch 60 { 61 Value = false; 62 } 63 return Value; 64 }