4

I have an event that takes about 10-30 seconds, namely downloading information from a page (with quite a lot of traffic), modifying it and then saving it somewhere onto the disk using WebClient. Because it takes such a long time, I want to add a progress bar or make an update label (which says something like updating..) to indicate the progress.

Can someone guide me as to how I would do this? Is there any event in the WebClient I can use to handle this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
david
  • 357
  • 2
  • 7
  • 18
  • http://sphotos.ak.fbcdn.net/hphotos-ak-snc4/hs892.snc4/72545_444026184526_748429526_5254434_3858588_n.jpg – Pedery Nov 13 '10 at 15:30

2 Answers2

30

If you're writing a Windows Forms client application (not a ASP.NET server-side component), showing the progress of a WebClient download can be done as follows:

WebClient webClient = new WebClient();
webClient.DownloadProgressChanged += (s, e) =>
{
    progressBar.Value = e.ProgressPercentage;
};
webClient.DownloadFileCompleted += (s, e) =>
{
    progressBar.Visible = false;
    // any other code to process the file
};
webClient.DownloadFileAsync(new Uri("http://example.com/largefile.dat"),
    @"C:\Path\To\Output.dat");

(progressBar is the ID of a ProgressBar object on your form.)

Bradley Grainger
  • 27,458
  • 4
  • 91
  • 108
  • 1
    What is the `(s, e)` bit here doing? – Moshe Mar 27 '11 at 05:03
  • 4
    @Moshe It's a lambda expression (http://msdn.microsoft.com/en-us/library/bb397687.aspx) that takes two arguments; here it's used to concisely add an anonymous delegate as an event handler. – Bradley Grainger Mar 27 '11 at 05:48
  • Hello, Bradley! I was wondering... Your answer is so superb, that I have a simple question about it. `DownloadFileAsync`, if I tried to download a `.exe` from the internet, directly into another `.exe`, would it "update" the `.exe`, with the downloaded `.exe`'s data? Using `DownloadFileAsync`? Example: I created an application(`.exe`), and it displays `Hello World` then closes; then I would create another one, saying `Goodbye World` instead, and upload it to a website -- If I download the `Goodbye World` file to the `Hello World` file, would it overwrite the old `.exe` with the new? Thanks! :) – Momoro Nov 06 '19 at 01:37
  • :D That's exactly what I wanted :) Thank you! – Momoro Nov 06 '19 at 03:53
  • Make sure the .exe is not running. – ScottMichaud Jan 04 '20 at 19:40
0

just add -Priority Foregroud to use Bitstransfer with max bandwidth available!

Start-BitsTransfer -Source 'https://example.com/myfile.zip' -Destination 'C:\myfolder\myfile.zip' -Priority Foreground -Description 'Dowloading myfile'
Andrea
  • 103
  • 8