使用Webclient.Uploadfile在文件上载期间获取上载进度

时间:2009-06-11 16:54:05

标签: c# .net vb.net webclient

我有一个使用webclient将文件上传到服务器的应用程序。 我想在文件上传过程中显示进度条。 我将如何实现这一目标?

2 个答案:

答案 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文档。