进度条和webclient

dav*_*vid 4 c# webclient download progress-bar

我有一个大约10-30秒的事件,即从页面下载信息(具有相当多的流量),修改它然后使用WebClient将其保存到磁盘上.因为它花了这么长时间,我想添加一个进度条或制作一个更新标签(比如说更新......)来表示进度.

有人可以指导我如何做到这一点吗?WebClient中是否有任何可用于处理此事件的事件?

Bra*_*ger 20

如果您正在编写Windows窗体客户端应用程序(而不是ASP.NET服务器端组件),则可以按如下方式显示WebClient下载的进度:

WebClient webClient = new WebClient();
webClient.DownloadProgressChanged += (s, e) =>
{
    progressBar.Value = e.ProgressPercentage;
};
webClient.DownloadFileCompleted += (s, e) =>
{
    progressBar.Visible = false;
    // any other code to process the file
};
webClient.DownloadFileAsync(new Uri("http://example.com/largefile.dat"),
    @"C:\Path\To\Output.dat");
Run Code Online (Sandbox Code Playgroud)

(progressBar是表单上ProgressBar对象的ID.)

  • @Moshe这是一个lambda表达式(http://msdn.microsoft.com/en-us/library/bb397687.aspx),它有两个参数; 这里它用于简洁地添加匿名委托作为事件处理程序. (4认同)