16

I have an app that uploads files to server using the webclient. I'd like to display a progressbar while the file upload is in progress. How would I go about achieving this?

Raj
  • 22,346
  • 14
  • 99
  • 142
Bruce Adams
  • 12,040
  • 6
  • 28
  • 37

2 Answers2

26

WebClient.UploadFileAsync will allow you to do this.

WebClient webClient = new WebClient();
webClient.UploadFileAsync(address, fileName);
webClient.UploadProgressChanged += WebClientUploadProgressChanged;

...

void WebClientUploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
        Console.WriteLine("Upload {0}% complete. ", e.ProgressPercentage);
}

Note that the thread won't block on Upload anymore, so I'd recommend using:

 webClient.UploadFileCompleted += WebClientUploadCompleted;

...

 void WebClientUploadCompleted(object sender, UploadFileCompletedEventArgs e)
 {
     // The upload is finished, clean up
 }
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Matt Brindley
  • 9,739
  • 7
  • 47
  • 51
  • Thanks. I'm working with multithreading, the file upload is already running on a different thread. So should I just use the Uploadfile method or the UploadfileAsync method? – Bruce Adams Jun 11 '09 at 17:12
  • You'll still need to UploadFileAsync I'm afraid, the thread will block on a call to UploadFile so those events will never get called. You can recreate your own blocking by setting a bool flag when you start the upload, reset it in uploadcomplete, then thread.sleep until the flag is cleared. – Matt Brindley Jun 11 '09 at 17:17
  • note: ```UploadProgressChanged``` event does not work well with ```UploadDataAsync``` method – Chauskin Rodion Jul 03 '17 at 16:18
  • How to pass parameters like FileName in WebClient? – Nirav Parsana Jul 11 '19 at 05:29
  • Did you use any cancelAsyc in your method. if yes how did you use it in a way the cancel upload stop on the spot and not wait to end the upload process to cancel? – H_H Dec 03 '19 at 09:58
2

Add your event handler to WebClient.UploadProgressChanged and call WebClient.UploadFileAsync.

See the WebClient.UploadProgressChanged documentation for an example.

AgentFire
  • 8,944
  • 8
  • 43
  • 90
ggponti
  • 395
  • 5
  • 9