Download a file from a web server

suggest change

Downloading a file from the internet is a very common task required by almost every application your likely to build.

To accomplish this, you can use the “System.Net.WebClient” class.

The simplest use of this, using the “using” pattern, is shown below:

using (var webClient = new WebClient())
    webClient.DownloadFile("", "C:\\file.txt");

What this example does is it uses “using” to make sure that your web client is cleaned up correctly when finished, and simply transfers the named resource from the URL in the first parameter, to the named file on your local hard drive in the second parameter.

The first parameter is of type “System.Uri”, the second parameter is of type “System.String

You can also use this function is an async form, so that it goes off and performs the download in the background, while your application get’s on with something else, using the call in this way is of major importance in modern applications, as it helps to keep your user interface responsive.

When you use the Async methods, you can hook up event handlers that allow you to monitor the progress, so that you could for example, update a progress bar, something like the following:

var webClient = new WebClient())
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync("", "C:\\file.txt");

One important point to remember if you use the Async versions however, and that’s “Be very carefull about using them in a ‘using’ syntax”.

The reason for this is quite simple. Once you call the download file method, it will return immediately. If you have this in a using block, you will return then exit that block, and immediately dispose the class object, and thus cancel your download in progress.

If you use the ‘using’ way of performing an Async transfer, then be sure to stay inside the enclosing block until the transfer completes.

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents