Force WebClient to use SSL

2020-04-08 12:09发布

问题:

I saw this post giving the simple idea of uploading files to ftp by using WebClient. This is simple, but how do I force it to use SSL?

回答1:

The answer here by Edward Brey might answer your question. Instead of providing my own answer I will just copy what Edward says:


You can use FtpWebRequest; however, this is fairly low level. There is a higher-level class WebClient, which requires much less code for many scenarios; however, it doesn't support FTP/SSL by default. Fortunately, you can make WebClient work with FTP/SSL by registering your own prefix:

private void RegisterFtps()
{
    WebRequest.RegisterPrefix("ftps", new FtpsWebRequestCreator());
}

private sealed class FtpsWebRequestCreator : IWebRequestCreate
{
    public WebRequest Create(Uri uri)
    {
        FtpWebRequest webRequest = (FtpWebRequest)WebRequest.Create(uri.AbsoluteUri.Remove(3, 1)); // Removes the "s" in "ftps://".
        webRequest.EnableSsl = true;
        return webRequest;
    }
}

Once you do this, you can use WebRequest almost like normal, except that your URIs start with "ftps://" instead of "ftp://". The one caveat is that you have to specify the method, since there won't be a default one. E.g.

// Note here that the second parameter can't be null.
webClient.UploadFileAsync(uploadUri, WebRequestMethods.Ftp.UploadFile, fileName, state);


标签: c# .net security