使用SSL的WebRequest

Pau*_*els 4 .net c# ftp ssl webrequest

我有以下代码使用FTP检索文件(工作正常).

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(svrPath);

            request.KeepAlive = true;
            request.UsePassive = true;
            request.UseBinary = true;

            request.Method = WebRequestMethods.Ftp.DownloadFile;
            request.Credentials = new NetworkCredential(uname, passw);

            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            using (Stream responseStream = response.GetResponseStream())
            using (StreamReader reader = new StreamReader(responseStream))
            using (StreamWriter destination = new StreamWriter(destinationFile))
            {
                destination.Write(reader.ReadToEnd());
                destination.Flush();
            }
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用SSL执行此操作时,我无法访问该文件,如下所示:

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(svrPath);

            request.KeepAlive = true;
            request.UsePassive = true;
            request.UseBinary = true;

            // The following line causes the download to fail
            request.EnableSsl = true;

            request.Method = WebRequestMethods.Ftp.DownloadFile;
            request.Credentials = new NetworkCredential(uname, passw);

            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            using (Stream responseStream = response.GetResponseStream())
            using (StreamReader reader = new StreamReader(responseStream))
            using (StreamWriter destination = new StreamWriter(destinationFile))
            {
                destination.Write(reader.ReadToEnd());
                destination.Flush();
            }
Run Code Online (Sandbox Code Playgroud)

谁能告诉我为什么后者不起作用?

编辑:

我得到以下异常:

The remote server returned an error: (530) Not logged in.
Run Code Online (Sandbox Code Playgroud)

mat*_*mc3 8

您在哪里验证SSL证书?通过FTP连接执行SSL并不像设置.EnableSsl属性那么简单.您需要提供证书验证方法.请参阅此文章,了解C#代码以执行您想要的操作.此外,如果您需要更详细的实现,有人会在此MSDN文章中复制并粘贴其整个FTP类.

为了快速启动并快速运行,请测试:

if (request.EnableSsl) ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
Run Code Online (Sandbox Code Playgroud)

然后:

public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
 return true; // Read the links provided above for real implementation
}
Run Code Online (Sandbox Code Playgroud)