How To

How To: Use the WebClient

Networking In The Hand includes the WebClient class which is a helper class which makes it easier to do uploading and downloading of data using HTTP and FTP transports. For example rather than creating an HttpWebRequest, setting a number of properties, getting the response and reading the response stream and copying the data into a file, why not use DownloadFile to perform a single operation to write the data from a specific Uri to a local file:-

WebClient wc = new WebClient();
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
   wc.DownloadFile(uriTarget, saveFileDialog1.FileName);

Additional methods provide the ability to download a string, and download a byte array containing the data. There are a similar set of operations for uploading:-

if (openFileDialog1.ShowDialog() == DialogResult.OK)
   wc.UploadFile(uriDestination, openFileDialog1.FileName);

Not only does this work with the HTTP transport, but also with the FTP support which is also part of the library – the only difference is the Uri that you pass in. If your site requires a username/password you can set the Credentials property of the WebClient once and they will be used for all subsequent operations.

By Peter Foot

Microsoft Windows Development MVP