C# 如何检查所有文件是否已下载?

C# 如何检查所有文件是否已下载?,c#,.net,winforms,C#,.net,Winforms,在我尝试检查progressBar2是否显示总体下载进度为100%之前,它并没有真正起作用。有没有其他更可靠的方法来检查它 private void btnDownload_Click(object sender, EventArgs e) { //urll.Add("http://download.thinkbroadband.com/1GB.zip"); btnDownload.Enabled = false;

在我尝试检查progressBar2是否显示总体下载进度为100%之前,它并没有真正起作用。有没有其他更可靠的方法来检查它

private void btnDownload_Click(object sender, EventArgs e)
        {
            //urll.Add("http://download.thinkbroadband.com/1GB.zip");
            btnDownload.Enabled = false;
            label7.Text = "Downloading...";
            getTotalBytes(countryList);
            CreateCountryDateTimeDirectories(newList);
            downloadFile(newList);
        }

        private Queue<string> _downloadUrls = new Queue<string>();

        private async void downloadFile(IEnumerable<string> urls)
        {
            foreach (var url in urls)
            {
                _downloadUrls.Enqueue(url);
            }

            await DownloadFile();
        }

        private async Task DownloadFile()
        {
            if (_downloadUrls.Any())
            {
                WebClient client = new WebClient();
                client.DownloadProgressChanged += ProgressChanged;
                client.DownloadFileCompleted += Completed;

                var url = _downloadUrls.Dequeue();

                sw = Stopwatch.StartNew();

                if (url.Contains("true"))
                {
                    await client.DownloadFileTaskAsync(new Uri(url), countriesMainPath + "\\" + currentDownloadCountry + "\\" + count + "Infrared.jpg");
                }
                else
                {
                    await client.DownloadFileTaskAsync(new Uri(url), countriesMainPath + "\\" + currentDownloadCountry + "\\" + count + "Invisible.jpg");
                }

                return;
            }
        }

        double percentageTotalDownload = 0;
        double totalBytesDownloaded = 0;
        private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            // Calculate download speed and output it to labelSpeed.
            label3.Text = string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));

            // Update the progressbar percentage only when the value is not the same.
            double bytesInCurrentDownload = (double)e.BytesReceived;
            double totalBytesCurrentDownload = double.Parse(e.TotalBytesToReceive.ToString());
            double percentageCurrentDownload = bytesInCurrentDownload / totalBytesCurrentDownload * 100;
            ProgressBar1.Value = int.Parse(Math.Truncate(percentageCurrentDownload).ToString());//e.ProgressPercentage;
                                                                                                // Show the percentage on our label.
            Label4.Text = e.ProgressPercentage.ToString() + "%";

            // Update the label with how much data have been downloaded so far and the total size of the file we are currently downloading
            label10.Text = string.Format("{0} MB's / {1} MB's",
                (e.BytesReceived / 1024d / 1024d).ToString("0.00"),
                (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));

            //Let's update ProgressBar2
            totalBytesDownloaded = e.BytesReceived + bytesFromCompletedFiles;
            percentageTotalDownload = totalBytesDownloaded / totalBytesToDownload * 100;
            progressBar2.Value = (int)percentageTotalDownload;
            label6.Text = progressBar2.Value.ToString() + "%";
        }

        long bytesFromCompletedFiles = 0;
        // The event that will trigger when the WebClient is completed
        private async void Completed(object sender, AsyncCompletedEventArgs e)
        {
          await DownloadFile();
        }
private void btnDownload\u单击(对象发送者,事件参数e)
{
//urll.Add(“http://download.thinkbroadband.com/1GB.zip");
btnDownload.Enabled=false;
label7.Text=“下载…”;
getTotalBytes(国家列表);
createCountryDateTimeDirectory(newList);
下载文件(新列表);
}
私有队列_downloadURL=new Queue();
私有异步void下载文件(IEnumerable URL)
{
foreach(url中的变量url)
{
_下载url.Enqueue(url);
}
等待下载文件();
}
私有异步任务下载文件()
{
if(_downloadUrls.Any())
{
WebClient客户端=新的WebClient();
client.DownloadProgressChanged+=ProgressChanged;
client.DownloadFileCompleted+=已完成;
var url=_downloadUrls.Dequeue();
sw=秒表。开始新();
if(url.Contains(“true”))
{
等待client.DownloadFileTaskAsync(新Uri(url),countriesMainPath+“\\”+currentDownloadCountry+“\\”+count+“Infrared.jpg”);
}
其他的
{
等待client.DownloadFileTaskAsync(新Uri(url),countriesMainPath+“\\”+currentDownloadCountry+“\\”+count+“Invisible.jpg”);
}
返回;
}
}
double percentageTotalDownload=0;
double totalBytesDownloaded=0;
私有void ProgressChanged(对象发送方,下载progresschangedeventargs e)
{
//计算下载速度并将其输出到labelSpeed。
label3.Text=string.Format(“{0}kb/s”,(e.BytesReceived/1024d/sw.appeased.TotalSeconds).ToString(“0.00”);
//仅当值不相同时更新progressbar百分比。
double bytesincrentdownload=(double)e.bytesinreceived;
double totalBytesCurrentDownload=double.Parse(例如,TotalBytesToReceive.ToString());
double percentageCurrentDownload=bytesInCurrentDownload/totalBytesCurrentDownload*100;
ProgressBar1.Value=int.Parse(Math.Truncate(percentageCurrentDownload.ToString());//e.ProgressPercentage;
//在我们的标签上显示百分比。
Label4.Text=e.ProgressPercentage.ToString()+“%”;
//用到目前为止下载的数据量和当前下载的文件的总大小更新标签
label10.Text=string.Format(“{0}MB/{1}MB”,
(e.BytesReceived/1024d/1024d)。ToString(“0.00”),
(e.TotalBytesToReceive/1024d/1024d).ToString(“0.00”);
//让我们更新ProgressBar2
totalBytesDownloaded=e.BytesReceived+bytesFromCompletedFiles;
percentageTotalDownload=TotalBytesDownload/TotalByTestToDownload*100;
progressBar2.Value=(int)percentageTotalDownload;
label6.Text=progressBar2.Value.ToString()+“%”;
}
long bytesFromCompletedFiles=0;
//WebClient完成时将触发的事件
私有异步无效已完成(对象发送方,AsyncCompletedEventArgs e)
{
等待下载文件();
}

例如,如果我有100个URL,它开始下载,那么我想在完成的事件中知道所有文件何时下载,而不是每次只下载一个。

我不是很了解它,但您试图实现的是,您的进度条显示了下载所有文件的进度,而不是一个文件然后重置,然后是另一个重置的文件

如果是这种情况,那么为什么不尝试为每个文件获取大小并将其相加到
TotalByTestToDownload
,然后在进度条中使用它呢

所以


您可以跟踪计数器变量中已完成的下载量。由于有多个线程可以访问该计数器,请使用该类来操作该计数器

以下是代码中所需的更改:

private int urlCount = 0; // keep track of how many urls are processed

private async void downloadFile(IEnumerable<string> urls)
{
    urlCount = 0;
    foreach (var url in urls)
    {
        _downloadUrls.Enqueue(url);
        urlCount++;
    }
    // urlCount is now set
    await DownloadFile();
}
private int urlCount = 0; // keep track of how many urls are processed

private async void downloadFile(IEnumerable<string> urls)
{
    urlCount = 0;
    foreach (var url in urls)
    {
        _downloadUrls.Enqueue(url);
        urlCount++;
    }
    // urlCount is now set
    await DownloadFile();
}
private async void Completed(object sender, AsyncCompletedEventArgs e)
{
    // urlCount will be decremented
    // cnt will get its value
    var cnt = System.Threading.Interlocked.Decrement(ref urlCount);

    if (cnt > 0) {
        await DownloadFile();
    } 
    else
    {
        // call here what ever you want to happen when everything is 
        // downloaded
        "Done".Dump();
    }
}