views:

1020

answers:

2

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?

+2  A: 

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("Download {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
 }
Matthew Brindley
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
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.
Matthew Brindley
A: 

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

See the WebClient.UploadProgressChanged documentation for an example.

ggponti