At first, I've written this code:
using (var client = new WebClient()) { client.Credentials = new NetworkCredential("user", "secret"); client.UploadFile("ftps://myserver/mypath/myfile.txt", path); }
First exception: The URI prefix is not recognized
. After some googling, I've found that I need to register the ftps
prefix like this:
sealed class FtpsWebRequestCreator : IWebRequestCreate { public static FtpsWebRequestCreator Instance { get; } = new(); public WebRequest Create(Uri uri) { // Removes the "s" in "ftps://". var webRequest = (FtpWebRequest)WebRequest.Create(uri.AbsoluteUri.Remove(3, 1)); webRequest.EnableSsl = true; return webRequest; } } WebRequest.RegisterPrefix("ftps", FtpsWebRequestCreator.Instance);
Next was This method is not supported
. This one was more difficult. In fact, you have to use an overload of UploadFile()
where you can pass the method to use (STOR
instead of POST
):
using (var client = new WebClient()) { client.Credentials = new NetworkCredential("user", "secret"); client.UploadFile("ftps://myserver/mypath/myfile.txt", WebRequestMethods.Ftp.UploadFile, path); }
Finally, AuthentificationException
. In fact, I'm using a self signed certificate, so I need to set a callback to accept all the certificates I'll find on my way (don't do this at home):
ServicePointManager.ServerCertificateValidationCallback = (_, _, _, _) => true;
Once again, a task that takes much longer than expected...