Download a file from a web server

suggest change

Downloading a file from the internet is a common task.

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("http://www.server.com/file.txt", "C:\\file.txt");
}

using disposes the client when the block ends. DownloadFile saves the resource at the address to the local path. The address can be a string or a Uri.

The async methods download in the background so the caller can keep working. That matters for a user interface, which stays responsive while the file transfers.

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("http://www.server.com/file.txt", "C:\\file.txt");

Be careful about using the async methods in a using block.

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:

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



Table Of Contents