标签:
1 using System; 2 using System.Net; 3 using System.IO; 4 using System.Net.Security; 5 using System.Security.Cryptography.X509Certificates; 6 7 namespace FtpWebrequestBlogCase 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 DownLoadFile("ftp://xxx/xxx.zip"); 14 Console.ReadKey(); 15 } 16 17 public static void DownLoadFile(string addr) 18 { 19 var req = (FtpWebRequest)WebRequest.Create(addr); 20 req.Method = WebRequestMethods.Ftp.DownloadFile; 21 req.UseBinary = true; 22 req.UsePassive = true; 23 const string userName = "xxxx"; 24 const string password = "xxxx"; 25 req.Credentials = new NetworkCredential(userName, password); 26 27 //如果要连接的 FTP 服务器要求凭据并支持安全套接字层 (SSL),则应将 EnableSsl 设置为 true。 28 //如果不写会报出421错误(服务不可用) 29 req.EnableSsl = true; 30 31 // 首次连接FTP server时,会有一个证书分配过程。 32 //如果没有下面的代码会报异常: 33 //System.Security.Authentication.AuthenticationException: 根据验证过程,远程证书无效。 34 ServicePointManager.ServerCertificateValidationCallback = 35 new RemoteCertificateValidationCallback(ValidateServerCertificate); 36 try 37 { 38 using (var res = (FtpWebResponse)req.GetResponse()) 39 { 40 const string localfile = "test.zip"; 41 var fs = new FileStream(localfile, FileMode.Create, FileAccess.Write); 42 const int buffer = 1024*1000; 43 var b = new byte[buffer]; 44 var i = 0; 45 var stream = res.GetResponseStream(); 46 while (stream != null && (i = stream.Read(b, 0, buffer)) > 0) 47 { 48 fs.Write(b, 0, i); 49 fs.Flush(); 50 } 51 } 52 Console.WriteLine("done!"); 53 54 } 55 catch (Exception ex) 56 { 57 var message = ex.ToString(); 58 Console.WriteLine(message); 59 } 60 finally 61 { 62 63 } 64 } 65 66 public static bool ValidateServerCertificate 67 (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) 68 { 69 return true; 70 } 71 } 72 }
C#从基于FTPS的FTP server下载数据 (FtpWebRequest 的使用)SSL 加密
标签:
原文地址:http://www.cnblogs.com/Jason-blogs/p/4556416.html