我有以下代码使用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();
}
但是,当我尝试使用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();
}
谁能告诉我为什么后者不起作用?
编辑:
我得到以下异常:
The remote server returned an error: (530) Not logged in.
答案 0 :(得分:8)
您在哪里验证SSL证书?通过FTP连接执行SSL并不像设置.EnableSsl
属性那么简单。您需要提供证书验证方法。有关C#代码,请参阅this article以执行所需操作。此外,如果您需要更详细的实施,有人会在this MSDN article中复制并粘贴整个FTP类。
为了快速启动并快速运行,请测试:
if (request.EnableSsl) ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
然后再说:
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
return true; // Read the links provided above for real implementation
}
答案 1 :(得分:-3)
试试这个 FtpWebRequest request =(FtpWebRequest)FtpWebRequest.Create(svrPath);