【发布时间】:2016-09-17 21:42:13
【问题描述】:
我正在尝试从我的网络服务器下载文件夹,并且我想在进度条上显示已下载/要下载的数据总数的进度。首先我尝试使用WebClient.DownloadFile。哪个工作完美,但没有触发DownloadProgressChangedEventHandler。我猜它只能通过异步下载激活。所以我将我的方法改写为WebClient.DownloadFileAsync。这就是复杂的地方。
例如,我的 Web 服务器上有 30 个文件,大小为 53 MB。我想下载所有 30 个文件并在进度条上显示下载进度(并在其下显示 xx/53 MB 下载的标签)。
//Inicialized by opening dialog
private void DownloadForm_Shown(object sender, EventArgs e) {
WebClient client = new WebClient();
client.DownloadProgressChanged += client_DownloadProgressChanged;
client.DownloadFileCompleted += client_DownloadFileCompleted;
startDownload();
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) {
progressBar.Value = e.ProgressPercentage;
labelProgress.Text = String.Format("Downloaded {0} of {1} bytes", e.BytesReceived, e.TotalBytesToReceive);
}
private void startDownload() {
//files contains all URL links
foreach (string str in files) {
string urlDownload = HttpUtility.UrlPathEncode(str);
//location is variable where file will be stored
client.DownloadFileAsync(new Uri(urlDownload), location);
//without this, async download will go crazy and wont download anything
while (client.IsBusy) { }
}
}
我有这段代码,发生的事情是它会开始下载,但不会更新进度条,也不会更新标签。然后在下载后它将在大约 0.5 秒内更新进度和标签,仅此而已。我是这类事情的初学者,你能帮我找出错误吗?我知道如何为一个文件制作进度条。但是我必须做些什么来制作多个文件?
编辑:可以在此处找到带有一些解决方案的完整代码:http://pastebin.com/Hu4CCY8M
但是调用downloadURLs() 方法后UI 会冻结。完成此方法后,它将重新开始工作。
【问题讨论】:
标签: c# .net asynchronous webclient