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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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
}
回答2:
Add your event handler to WebClient.UploadProgressChanged and call WebClient.UploadFileAsync.
See the WebClient.UploadProgressChanged documentation for an example.