使用C#中的代理连接到FTPS

时间:2017-12-28 09:12:09

标签: c# .net ftp ftpwebrequest ftps

我的下面的代码在没有代理的计算机上运行得很好。但是在客户端服务器中,他们需要向FTP客户端(FileZilla)添加代理才能访问FTP。但是当我添加代理时,它说

  

使用代理时无法启用SSL。

FTP代理

var proxyAddress = ConfigurationManager.AppSettings["ProxyAddress"];
WebProxy ftpProxy = null;
if (!string.IsNullOrEmpty(proxyAddress))
{
   var proxyUserId = ConfigurationManager.AppSettings["ProxyUserId"];
   var proxyPassword = ConfigurationManager.AppSettings["ProxyPassword"];
    ftpProxy = new WebProxy
    {
        Address = new Uri(proxyAddress, UriKind.RelativeOrAbsolute),
        Credentials = new NetworkCredential(proxyUserId, proxyPassword)
    };
 }

FTP连接

var ftpRequest = (FtpWebRequest)WebRequest.Create(ftpAddress);
ftpRequest.Credentials = new NetworkCredential(
                            username.Normalize(), 
                            password.Normalize()
                         );

ServicePointManager.ServerCertificateValidationCallback += 
   (sender, cert, chain, sslPolicyErrors) => true;

ServicePointManager.Expect100Continue = false;

ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
ftpRequest.EnableSsl = true;
//ftpRequest.Proxy = ftpProxy;
var response = (FtpWebResponse)ftpRequest.GetResponse();

1 个答案:

答案 0 :(得分:3)

.NET框架确实不支持代理上的TLS / SSL连接。

您必须使用第三方FTP库。

另请注意,您的代码未使用"隐式" FTPS。它正在使用" explicit" FTPS。 Implicit FTPS is not supported by .NET framework也是。

例如,使用WinSCP .NET assembly,您可以使用:

// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Ftp,
    HostName = "example.com",
    UserName = "user",
    Password = "mypassword",
    FtpSecure = FtpSecure.Explicit, // Or .Implicit
};

// Configure proxy
sessionOptions.AddRawSettings("ProxyMethod", "3");
sessionOptions.AddRawSettings("ProxyHost", "proxy");

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    var listing = session.ListDirectory(path);
}

有关SessionOptions.AddRawSettings的选项,请参阅raw settings

(我是WinSCP的作者)