开发者

WebRequest using SSL

I have the following code to retrieve a file using FTP (which works fine).

            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();
            }

However, when I try to do this using SSL, I am unable to access the file, as follows:

            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();
            }

Can anyone tell me why the latter would not work?

EDIT:

I get the following exception:

The remote server returne开发者_运维技巧d an error: (530) Not logged in.


Where do you validate the SSL certificate? Doing SSL over an FTP connection isn't quite as simple as setting the .EnableSsl property. You need to provide a certificate validation method. See this article for the C# code to do what you want. Also, someone copied and pasted their whole FTP class in this MSDN article if you need a more detailed implementation.

Just to quickly get you up and running quickly, test with this:

if (request.EnableSsl) ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);

and then later:

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


Try this FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(svrPath);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜