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 = *;
var b = new byte[buffer];
var i = ;
var stream = res.GetResponseStream();
while (stream != null && (i = stream.Read(b, , buffer)) > )
{
fs.Write(b, , 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;
}
{
return true;
}
证书验证过程。
下篇文章将探讨如何封装FTPWebRequest类,使其更加健壮易用。