public void DownloadFile(string urlAddress, string location)
{
Stopwatch sw = new Stopwatch();
using (WebClient webClient = new WebClient())
{
webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0 Chrome");
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler((sender, e) => Completed(sender, e, sw));
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sender, e) => ProgressChanged(sender, e, sw));
Uri URL = new Uri(urlAddress);
sw.Start();
try
{
webClient.DownloadFileAsync(URL, location);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e, Stopwatch sw)
{
string downloadProgress = e.ProgressPercentage + "%";
string downloadSpeed = string.Format("{0} MB/s", (e.BytesReceived / 1024.0 / 1024.0 / sw.Elapsed.TotalSeconds).ToString("0.00"));
string downloadedMBs = Math.Round(e.BytesReceived / 1024.0 / 1024.0) + " MB";
string totalMBs = Math.Round(e.TotalBytesToReceive / 1024.0 / 1024.0) + " MB";
// Format progress string
string progress = $"{downloadedMBs}/{totalMBs} ({downloadProgress}) @ {downloadSpeed}"; // 10 MB / 100 MB (10%) @ 1.23 MB/s
progressBarText1.Value = e.ProgressPercentage;
progressBarText1.Refresh();
progressBarText1.CustomText = progress;
}
private void Completed(object sender, AsyncCompletedEventArgs e, Stopwatch sw)
{
if (e.Cancelled == true)
{
btnStartDownload.Text = "Fails.";
sw.Stop();
}
else
{
btnStartDownload.Text = "Finish.";
sw.Stop();
if (videosLinks.Count > 0)
{
videosLinks.RemoveAt(0);
string fileName = System.IO.Path.GetFileName(videosLinks[0]);
DownloadFile(videosLinks[0], @"D:\Videos\videos\" + fileName);
}
}
}
static readonly string[] SizeSuffixes =
{ "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
static string SizeSuffix(Int64 value, Int64 totalValue)
{
if (value < 0) { return "-" + SizeSuffix(-value, totalValue); }
int i = 0;
decimal dValue = (decimal)value;
while (Math.Round(dValue / 1024) >= 1)
{
dValue /= 1024;
i++;
}
return string.Format("{0:n1} {1} {2}", dValue, SizeSuffixes[i], (totalValue / 1024d / 1024d).ToString("0.00"));
}
这是正常的,但它报告的是每个文件的下载进度。
我如何才能使它也将报告整体下载的进度?我添加了另一个名为progressBar2的进度条,我想报告整体下载过程,而不是像我对progressBar1所做的那样按文件报告。
1条答案
按热度按时间gt0wga4j1#
这是一个可行的解决方案。
progressBarText类型是一个自定义进度栏: