FTPS,亦或是FTPES, 是FTP協議的一種擴展,用於對TLS和SSL協議的支持。
本文講述了如何從一個基於FTPS的Server中下載數據的實例。
任何地方,如有紕漏,歡迎諸位道友指教。
話不多,上碼。

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 }
其實之比正常的FTP下載文件函數多了兩句代碼:
1 req.EnableSsl = true; 基於FTPS的 FTP 服務器會要求憑據並支持安全套接字層 (SSL),所以需要設置為True.
2 ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(ValidateServerCertificate);
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
{
return true;
}
證書驗證過程。
下篇文章將探討如何封裝FTPWebRequest類,使其更加健壯易用。