Timothy Khouri - SingingEels.com

I subscribe to the "take it apart and rebuild it" approach to learning.

Downloading and uploading to an FTP the easy way!

One of my biggest passions when it comes to programming has always been communication between computers (and networks), whether it be with raw communication with Sockets, Web Services, remoting or whatever. Just the thought of all that's going on behind the scenes to "connect" everyone together really blows my mind.

Along that line of thought is one of my favorite classes in the .NET framework, the WebClient class (in the System.Net namespace). I've always known of this class to upload and download files from a web server, but you can also use it for FTP servers too.

So without boring with too much talking, I'll show you how easy it is with some code:

// Make an instance of the WebClient class.
 WebClient myLilWebClient = new WebClient();

// Since my FTP requires authentication, I'll have to supply my
// UserName and Password.
myLilWebClient.Credentials = new NetworkCredential("userName", "p@ssw0rd");

// Now I'll download a file from my FTP right to my desktop.
myLilWebClient.DownloadFile("ftp://myFtpAddress.com/somefile.txt", @"c:\documents and settings\tkhouri\desktop\somefile.txt");

I don't think it could get any easier than that! Oh, and if you wanted to Upload a file to an FTP... you'd simply call mYLilWebClient.UploadFile.

Gotta love .NET!

Comments

hristo.deshev said:

Thanks for the tip! The best part about it is that you can script that in PowerShell in about the same amount of code and automate a deployment process and whatnot.

# September 8, 2007 1:31 PM

Wim Hollebrandse said:

It's still a very poor implementation considering all the functionality that an FTP client should have.

A half-baked effort on MS' part as far as I'm concerned.

If you want a fully functional FTP client - read the RFC's and roll your own. Now that's fun. ;-)

# September 8, 2007 7:30 PM

jayson knight said:

Is there something wrong with the built in FtpWebRequest class in System.Net?

msdn2.microsoft.com/.../system.net.ftpwebrequest.aspx

# September 9, 2007 3:39 PM

Vikram said:

why not use the built in FtpWebRequest class for FTP?

# September 10, 2007 12:39 AM

Nullable said:

You can use the FtpWebRequest... but that's a lot more work. You could even use regular old Tcp Sockets and write all the byte data yourself!

It's just very easy to say "DownloadFile" which will do all the FtpWebRequest stuff, and all the File IO stuff etc :)

# September 10, 2007 7:41 AM