1

I am trying to download a file with a webclient from a server. This works very good. But when I try to show the download progress in a progress bar, it does not give me any progress to see.

I am trying to download the file with the DownloadFileAsync-method to have an own thread for it all in order to prevent performance problems or freezes.

I declared the WebClient outside any subs or events:

private WebClient updateDownloader = new WebClient();

This looks like that in the Form.Shown-Event:

updateDownloader.DownloadFileAsync(new Uri(UriGoesHere), PathToSave);

It is in a Try-Block.

I created a sub like that to show the progress to the progressbar:

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

In the Form-Load-Event I created the eventhandler:

updateDownloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);

This should work in theory, but it does not, I already visited MSDN and saw some information that only some methods are working, but implementing this did not help.

It never reaches this one. What am I doing wrong? If you need some more code parts, tell me.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Dominic B.
  • 1,897
  • 1
  • 16
  • 31
  • Read this [answer](http://stackoverflow.com/questions/9459225/asynchronous-file-download-with-progress-bar). This good sample. – Mr.kto Jan 05 '14 at 22:14
  • Mr.kto Unfortunately this did not help, because the op in this thread just had the problem with freezing, but as he fixed that, he could see the progress. I think, my code is pretty much the same, but I cannot find the error. I think, I am just totally blind because I am dealing with that now since an hour. – Dominic B. Jan 05 '14 at 22:20
  • What is the file size? is it too big? or have slow connection? Can you try this label1.Text = e.BytesReceived.ToString(); in your ProgressChanged event and see if you get any result! – Deja Vu Apr 19 '14 at 15:41
  • I solved it already. I just set the event handler at the wrong position. – Dominic B. Apr 20 '14 at 07:57

2 Answers2

0

Did you try to modify your 'Form Shown' Event to be:

Application.DoEvents();
updateDownloader.DownloadFileAsync(new Uri(UriGoesHere), PathToSave);
Deja Vu
  • 413
  • 3
  • 6
-1

You need to update the progresbar from the main UI thread. You can't update UI from other thread directly.

user436862
  • 867
  • 2
  • 15
  • 32