在屏幕截图中,下载速度 = 显示无穷大符号 kb/s 而不是速度。
第一个下载文件显示速度很好,但从第二个下载文件显示无穷大符号。如何修复它以便显示每个文件的速度?
下载方法:
private async Task DownloadAsync()
{
using (var client = new WebClient())
{
client.DownloadFileCompleted += (s, e) => lblStatus.Text = "Download File Completed.";
client.DownloadFileCompleted += (s, e) => sw.Reset();
client.DownloadProgressChanged += (s, e) => progressBar1.Value = e.ProgressPercentage;
client.DownloadProgressChanged += (s, e) => lblAmount.Text = FormatBytes(e.BytesReceived);
client.DownloadProgressChanged += (s, e) => lblSpeed.Text = string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));
client.DownloadProgressChanged += (s, e) => lblDownloadSize.Text = Convert.ToInt64(client.ResponseHeaders["Content-Length"]).ToString();
client.DownloadProgressChanged += (s, e) =>
{
lblDownloadProgress.Text = "%" + e.ProgressPercentage.ToString();
lblDownloadProgress.Left = Math.Min(
(int)(progressBar1.Left + e.ProgressPercentage / 100f * progressBar1.Width),
progressBar1.Width - lblDownloadProgress.Width
);
};
for (int i = 0; i < urls.Count; i++)
{
await client.DownloadFileTaskAsync(new Uri(urls[i]), @"d:\satImages\img" + i + ".gif");
}
}
}
格式化字节方法:
private string FormatBytes(long bytes)
{
string[] Suffix = { "B", "KB", "MB", "GB", "TB" };
int i;
double dblSByte = bytes;
for (i = 0; i < Suffix.Length && bytes >= 1024; i++, bytes /= 1024)
{
dblSByte = bytes / 1024.0;
}
return String.Format("{0:0.00} {1}", dblSByte, Suffix[i]);
}
并在一个按钮单击事件中启动它:
private async void btnStart_Click(object sender, EventArgs e)
{
lblStatus.Text = "Downloading...";
sw.Start();
await DownloadAsync();
}