本文主要是介绍C#从基于FTPS的FTP server下载数据 (FtpWebRequest 的使用)SSL 加密,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
FTPS,亦或是FTPES, 是FTP协议的一种扩展,用于对TLS和SSL协议的支持。
本文讲述了如何从一个基于FTPS的Server中下载数据的实例。
任何地方,如有纰漏,欢迎诸位道友指教。
话不多,上码。
using System;using System.Net;using System.IO;using System.Net.Security;using System.Security.Cryptography.X509Certificates;namespace FtpWebrequestBlogCase{class Program{static void Main(string[] args){DownLoadFile("ftp://xxx/xxx.zip");Console.ReadKey();}public static void DownLoadFile(string addr){var req = (FtpWebRequest)WebRequest.Create(addr);req.Method = WebRequestMethods.Ftp.DownloadFile;req.UseBinary = true;req.UsePassive = true;const string userName = "xxxx";const string password = "xxxx";req.Credentials = new NetworkCredential(userName, password);//如果要连接的 FTP 服务器要求凭据并支持安全套接字层 (SSL),则应将 EnableSsl 设置为 true。//如果不写会报出421错误(服务不可用)req.EnableSsl = true;// 首次连接FTP server时,会有一个证书分配过程。//如果没有下面的代码会报异常://System.Security.Authentication.AuthenticationException: 根据验证过程,远程证书无效。ServicePointManager.ServerCertificateValidationCallback =new RemoteCertificateValidationCallback(ValidateServerCertificate);try{using (var res = (FtpWebResponse)req.GetResponse()){const string localfile = "test.zip";var fs = new FileStream(localfile, FileMode.Create, FileAccess.Write);const int buffer = 1024*1000;var b = new byte[buffer];var i = 0;var stream = res.GetResponseStream();while (stream != null && (i = stream.Read(b, 0, buffer)) > 0){fs.Write(b, 0, i);fs.Flush();}}Console.WriteLine("done!");}catch (Exception ex){var message = ex.ToString();Console.WriteLine(message);}finally{}}public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors){return true;}}}
其实之比正常的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;
}
证书验证过程。
下篇文章将探讨如何封装FTPWebRequest类,使其更加健壮易用。
这篇关于C#从基于FTPS的FTP server下载数据 (FtpWebRequest 的使用)SSL 加密的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!