Force WebClient to use SSL

前端 未结 1 369
醉话见心
醉话见心 2021-01-19 00:10

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条回答
  • 2021-01-19 00:45

    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);
    
    0 讨论(0)
提交回复
热议问题