Web Design that taps into the haromny and vision of your dreams.

How to Download Files With C# from a Web Server

A guide to downloading files from the web with C#

Written By on in C#

276 words, estimated reading time 2 minutes.

Microsoft .Net framework provides a set of classes that manage Internet communications and one, in particular, can be used to download a file from the internet to the local hard drive. This can be used to download a data set, for example, or to download program updates.

Microsoft .Net framework provides a set of classes that manage Internet communications and one in particular can be used to download files with C# from the internet to the local hard drive. This can be used to download a data set, for example, or to download program updates.

There are two methods for downloading a file, synchronously and asynchronously.

Synchronous Download

A Synchronous download will only allow one download to be processed, and while it is being processed, the main program thread will pause until the download is complete. It is the simplist method to implement, and if you can wait for the download to complete, it is often the best method to use.

using System.Net;
 
using(WebClient fileDownloader = new WebClient())
{
  fileDownloader.DownloadFile("https://timtrott.co.uk/robots.txt", "c:\robots.txt");
}

Asynchronous Download

An asynchronous download does not block the main program thread apart from the initial DNS lookup (converting a hostname to an IP address). Using an IP address directly can avoid this delay. This method is a bit more involved, but if you cannot wait for the download to finish, of if you need to download a large file this is the best method to use.

using System.Net;
 
using(WebClient fileDownloader = new WebClient())
{
  fileDownloader.DownloadFileAsync("https://timtrott.co.uk/robots.txt", "c:\robots.txt");
}

The Asynchronous Download method also contains a few events that can be used for progress bars and notifications and an event that is triggered on completion of the download.

 
...
fileDownloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(updateProgress);
...
 
private void updateProgress(object sender, DownloadProgressChangedEventArgs Arg)
{
  progressBar.Value = Arg.ProgressPercentage;
}

Last updated on: Wednesday 27th June 2018

 

Comments

There are no comments for this post. Be the first!

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me