Uploading and Downloading a File to an FTP Server Using C#

Simple FTP client code for when you're in a pinch.
Feb 09 2009 by James Craig

I've never been a big fan of FTP servers (or IRC, or really anything where the average/popular tool is a pain to deal with).  That being said, I've had to use it quite a bit considering what I do for a living. To be honest though, I don't like the tools that are out there for dealing with it. So as always I decided to roll my own. I'm not going to give out all of the code, but I figured it would be nice to show how to download, as well as upload, a file to an FTP server:

  public static string GetFileContents(Uri FileName, string UserName, string Password)
{
WebClient Client = null;
StreamReader Reader = null;
try
{
Client = new WebClient();
Client.Credentials = new NetworkCredential(UserName, Password);
Reader = new StreamReader(Client.OpenRead(FileName));
string Contents = Reader.ReadToEnd();
Reader.Close();
return Contents;
}
catch
{
return "";
}
finally
{
if (Reader != null)
{
Reader.Close();
}
}
}



public static void SaveFile(string Content, string FileName, Uri FTPServer, string UserName, string Password)
{
try
{
Uri TempURI = new Uri(Path.Combine(FTPServer.ToString(), FileName));
FtpWebRequest FTPRequest = (FtpWebRequest)FtpWebRequest.Create(TempURI);
FTPRequest.Credentials = new NetworkCredential(UserName, Password);
FTPRequest.KeepAlive = false;
FTPRequest.Method = WebRequestMethods.Ftp.UploadFile;
FTPRequest.UseBinary = true;
FTPRequest.ContentLength = Content.Length;
FTPRequest.Proxy = null;
using (Stream TempStream = FTPRequest.GetRequestStream())
{
System.Text.ASCIIEncoding TempEncoding = new System.Text.ASCIIEncoding();
byte[] TempBytes = TempEncoding.GetBytes(Content);
TempStream.Write(TempBytes, 0, TempBytes.Length);
}
FTPRequest.GetResponse();
}
catch { }
}

Those two functions are all that is needed to accomplish what you want. GetFileContents downloads the file (although it only works for text files, it can easily be modified for binary). As input it takes in the location of the file that you want to download (which should include the ftp://servername/ portion), the user name needed for connecting to the server, and the password. Note that if it allows anonymous access, leaving those blank will work. The SaveFile function on the other hand will upload the file to an FTP server. That function needs a bit more information, the content that you wish to put in the file, the file name (which should include the directory information), the server name (once again, use the ftp://servername/), and once again the user name and password. You could modify the code to simply open and copy the file, I just didn't have the need at that level. Anyway, that's all there is to it and I hope this helps you out. So try it out, leave feedback, and happy coding.