Download a ﬁle from a web server C# with Example
Downloading a ﬁle from the internet is a very common task required by almost every application your likely to
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())
What this example does is it uses "using" to make sure that your web client is cleaned up correctly when ﬁnished,
and simply transfers the named resource from the URL in the ﬁrst parameter, to the named ﬁle on your local hard
drive in the second parameter.
The ﬁrst 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 oﬀ 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);
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 ﬁle 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