我有一个使用webclient将文件上传到服务器的应用程序。 我想在文件上传过程中显示进度条。 我将如何实现这一目标?
答案 0 :(得分:24)
WebClient.UploadFileAsync将允许您这样做。
WebClient webClient = new WebClient();
webClient.UploadFileAsync(address, fileName);
webClient.UploadProgressChanged += WebClientUploadProgressChanged;
...
void WebClientUploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
Console.WriteLine("Upload {0}% complete. ", e.ProgressPercentage);
}
请注意,线程不会再在上传时阻止,所以我建议使用:
webClient.UploadFileCompleted += WebClientUploadCompleted;
...
void WebClientUploadCompleted(object sender, UploadFileCompletedEventArgs e)
{
// The upload is finished, clean up
}
答案 1 :(得分:2)
将您的事件处理程序添加到WebClient.UploadProgressChanged并调用WebClient.UploadFileAsync。
有关示例,请参阅WebClient.UploadProgressChanged文档。