How to download a file in C# (progressbar and download speed)
This is a simple snippet that will allow you to download a file from the internet in C# while being able to display the download percentage, download speed and the amount of total data received while downloading.
This is the example form of what to expect when you have the code in place:
On to some code!
First we need to import three new namespaces in addition to the ones we already have.
1 2 3 | using System.Diagnostics; using System.IO; using System.Net; |
Then we add the two following global variables.
1 2 | WebClient webClient; // Our WebClient that will be doing the downloading for us Stopwatch sw = new Stopwatch(); // The stopwatch which we will be using to calculate the download speed |
Then finally we have our main methods that will do all the handling and displaying of the information.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | public void DownloadFile(string urlAddress, string location) { using (webClient = new WebClient()) { webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed); webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged); // The variable that will be holding the url address (making sure it starts with http://) Uri URL = urlAddress.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ? new Uri(urlAddress) : new Uri("http://" + urlAddress); // Start the stopwatch which we will be using to calculate the download speed sw.Start(); try { // Start downloading the file webClient.DownloadFileAsync(URL, location); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } // The event that will fire whenever the progress of the WebClient is changed private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e) { // Calculate download speed and output it to labelSpeed. labelSpeed.Text = string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00")); // Update the progressbar percentage only when the value is not the same. progressBar.Value = e.ProgressPercentage; // Show the percentage on our label. labelPerc.Text = e.ProgressPercentage.ToString() + "%"; // Update the label with how much data have been downloaded so far and the total size of the file we are currently downloading labelDownloaded.Text = string.Format("{0} MB's / {1} MB's", (e.BytesReceived / 1024d / 1024d).ToString("0.00"), (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00")); } // The event that will trigger when the WebClient is completed private void Completed(object sender, AsyncCompletedEventArgs e) { // Reset the stopwatch. sw.Reset(); if (e.Cancelled == true) { MessageBox.Show("Download has been canceled."); } else { MessageBox.Show("Download completed!"); } } |
That’s pretty much it. You just need call the DownloadFile
method with the URL address you want to download the file from and the place you want to save it to as arguments.
The above snippet uses labels to show the information (download speed, percentage, number of kilobytes downloaded) but feel free to modify the snippet to suit your needs.
hello guys. i have a question any one can share source code with ready to open in VS
Hi Bob
I am having same problem of download complete but nothing is happening
Can you help to resolve the problem.
If yes i can send you my code
Regards
Olukay
How can we change the progress download color from green to anyother color
how can I add that when the button is clicked this script happens?
Thanks youe code is working fine,
But full file is not download.
For example i have file size 4 mb in ZIP
but only 6 kb is downloaded.
Hi Iam new to c# programming. I have been trying to cancel my download by using the code webClient.CancelAsync();
i have a cancel button after clicking on it this is what i got
and then i entered webClient.CancelAsync(); inside the method but its not working.
I need help on this. Thank You in advance
This is a good program, easy & short.
How I can calculated the aprox time to finish the download?
Any idea?
Thanks! So much!
I can’t get this to work, i added a button(button1):
It just says complete when i press button1, no labels update and it doesnt download anything any ideas? Does it need to be ran as admin?
I understand now….
The download path needs to have the filename and extension included if you dont specify the filname and extension in the location path it wont download.
hi
i have same problem but it solved by your solution. tnx
In line 6 you need to add the file name, not just the folder path.
Hi Bob
I am having same problem of download complete but nothing is happening
Can you help to resolve the problem.
If yes i can send you my code
Regards
Olukay
Hi, thank You for sharing Your code. Everything works fine, as expected.
What I’m trying to add is ability to get original file name from server (if for example download url looks like this: . Below is code I’m adding before I call
When I click Save file first time everything works fine, but after second click I only get file name, download isn’t starting. Without that code I’m able to download file multiple times – I click button, get message box, click button and so on. With above code when I click button second time (after first download finish) nothing happens.
Could You please help me solve that?
Hopefully you can help. I’m new to this and im really in need of getting this to work. When I click my button to start the whole process I just instantly get the Download complete message box but nothing has downloaded. Do you know which direction to point me in? Thank you in advance
Ahhh Im dumb and figured it out! now I do have another question. Lets say I want to download 3 files at once using one button. How would I got about doing this that after one finishes the next starts! I do appreciate it!
What was the simple mistake Chris?
how to show percentage with decimals?
How to add the link for the download file ?
Hi,
very nice Stuff.
I used ur code and it works fine in the “real World”.
But what i need to insert, if i must use a proxy?
If i try to use it “as is” i get a 401-Error from the (Proxy?)Server.
Its a company-wide rule, and i can not see the settings, i do not need any User or PW, just using the system settings for the Proxy.
Any hints? Thank Thee.
You can use WebClient’s Proxy property to set the proxy but adding the following line under the using statement in the DownloadFile method:
thank You for the quick answer.
I do not have a adress/port for the proxy. The Proxy in the company is automaticly configures by a script that the normal user can not touch.
I need something like
“webClient.Proxy = WebRequest.GetSystemWebProxy();”
what would the example therefor look like, please?
The code you mentioned is actually correct.
WebRequest.GetSystemWebProxy will give you the system’s proxy server, which is what is under Control Panel -> Internet Options -> Connections -> Lan Settings.
If the company’s script uses another method to enforce the proxy (not using the system’s proxy settings) then this will not work.
OK, seems to be a Problem with httpS-Connections. If i try to reach http-Server it works. Thank Thee.
please add pause/resume support for this project….
Ok. I have gotten the code and its working mostly… When you goto download the file it makes not attempt to download it. It just says that the file has been downloaded. All the Lables and Buttons (also the loading bar) are named correct and Im getting no errors. Its just not downloading. Any Ideas?
I got Message “Download completed!” instantly without downloading or error.
Can you Help me?
Don’t forget to clean up the eventhandlers int the Completed event, otherwhise the function will give unexpected results when you use it multiple times in a row
hi,thank’s
a problem:
i’m disconnect from internet and call DownloadFile method!
app show massage(“Download Complete!”) and a file with 0KB created(string location)!!!
how to resolve this problem and show error when the connection don’t exist?
@Amin: in AsyncCompletedEvent
which arguments i do enter in webClient.CancelAsync();????
If I want to Download a file to the applications executing directory with a set URL to download the file.
Sorry it’s a n00by question I’m new to c#…
Hi,
Give the project file ?
Hi Rob,
Which project file you are asking about
The Visual Studio Project File (Project of Visual Studio) to download.
Solution to Download
How to upload a file in windows application and also i have to show how much it is upload in progress bar , please help me out
Good day.
Execllent code.
i am stuck on how to exactly pause and resume the download, do i cancel it first and then recall download passing the header with the bytes to continue?
when i do that it just goes straight to ‘download complete’.
i have a variable that holds the current bytes received, and i do pass it to the header. what am i missing here?
thanks in advance.
Thank You For Above Coding But in my application i have to upload file with percentage as you have done in this application please help me
Hi Fluxbyte.
I am using above code but my downloaded file is of 0 Kb in size. I have called File Download Method firstly on form_load and after that on Button Click.
I am trying to download an file which is of 6 mb in size and its extension is .EXE .
Please Help
Hi,
How multiple files to download ?
Hi fluxbytes,
this is awesome explanation each and everything step by step in commented
Thank you so much,
this saved my time also..
Thanks
Shravan.
Excelente, me sirvió mucho.
Muchas gracias.
Yea of Course !
gracias
How to download a file from an protected folder with username and password?
Can you help me ?
I get error “Infinity” where : labelSpeed.Text = string.Format(“{0} kb/s”, (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString(“0.00”));
Oh I’ve fixed it. I forgot sw.Start (). thanks!
I’m trying to figure out how to use the CancelAsync() method.
I look at a few MSDN articles, but I’m new to programming.
Can you please give me an example to follow.
Thanks,
Mike
So you have a Stop Button
What do you put in to stop the download?
Click Event so on?
To cancel the async operation of a WebClient object you will need to use its CancelAsync() method.
Hi
I’ve downloaded all the files but the program files with the extension. Xlsx I can not open
please help me
this is profect code.
I have another question.How can I Back the download complete bool flag to main thread ?
Depends what you want to do exactly. If you simply want to announce to the user that the download has been completed when the downloading is taking place in another thread you will need to invoke that control.
Example:
what about resuming the download..?
You will need to add and specify the range header.
Change 200 with the value you would want to continue from.
Hey, at beginning sorry for my English.
You code is great but i don’t understand how to resuming download. When I add
webClient.Headers.Add(HttpRequestHeader.Range, “”);
before
webClient.DownloadFileAsync(URL, location);
I get Message “Download completed!” instantly without downloading or error.
Can you Help me?
You need to specify the offset. As an example, the above code will skip the first 200 bytes.
The idea is to monitor how much bytes have been downloaded in order to know how many bytes to skip when you are resuming the download.
Yes I know this is only exemple:)
But even when i add correct value I get Message “Download completed!” instantly. Something is missing.
Thanks anyway.
webclient will not accept range headers
I am regular visitor, how are you everybody? This piece
of writing posted at this web site is really good.
I have one c# based application. what i want to do is display the csv files present in the folder in a list and facilitate the user to download the specific file to the local pc when one user clicks on the link.
Wow, marvelous blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your web site is fantastic, as well as the content!
I was looking for something like this for a while now. Thanks for sharing !