C# 使用 Webclient.Uploadfile 获取文件上传过程中的上传进度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/982299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:50:04  来源:igfitidea点击:

Getting the upload progress during file upload using Webclient.Uploadfile

c#.netvb.netwebclient

提问by Bruce Adams

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?

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

采纳答案by Matt Brindley

WebClient.UploadFileAsyncwill allow you to do this.

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);
}

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
 }

回答by ggponti

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

将您的事件处理程序添加到 WebClient.UploadProgressChanged 并调用 WebClient.UploadFileAsync。

See the WebClient.UploadProgressChangeddocumentation for an example.

有关示例,请参阅WebClient.UploadProgressChanged文档。