FTPS (FTP over SSL) in C#

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 WebClient almost like normal, except that your URIs start with “ftps://” instead of “ftp://”. The one caveat is that you have to specify the method parameter, since there won’t be a default one. E.g.

using (var webClient = new WebClient()) {
    // Note here that the second parameter can't be null.
    webClient.UploadFileAsync(uploadUri, WebRequestMethods.Ftp.UploadFile, fileName, state);
}

Leave a Comment