Thursday 17 May 2012

Simple FTP file upload in C# 2.0

Sometimes you just want a simple function to perform a simple task. There are a lot of FTP libraries for free download on the Internet, but if you simply want to upload a file to an FTP server in C#, these libraries are overkill for that simple little task. That's what I thought when I browsed the web for such a simple little function. Maybe I'm slower than normal people, but I couldn't find any simple method on the web. They where all too complicated, so I thought to myself that I could do better.
Here's what I came up with:
private static void Upload(string ftpServer, string userName, string password, string filename)
{
   using (System.Net.WebClient client = new System.Net.WebClient())
   {
      client.Credentials = new System.Net.NetworkCredential(userName, password);
      client.UploadFile(ftpServer + "/" + new FileInfo(filename).Name, "STOR", filename);
   }
}

Then call the method with the right parameters, and you're set to go:
Upload("ftp://ftpserver.com", "TheUserName", "ThePassword", @"C:\file.txt");
Can it get any simpler than that?

No comments:

Post a Comment