Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force WebClient to use SSL

Tags:

c#

.net

security

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?

like image 953
ispiro Avatar asked Jul 15 '15 13:07

ispiro


1 Answers

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);
like image 185
Thorsten Dittmar Avatar answered Oct 05 '22 23:10

Thorsten Dittmar