在一个进度条上下载多个文件

时间:2018-09-25 10:59:02

标签: c# winforms

我有时有1个,有时有4-5个要下载。 而且我不希望每个文件的进度条都重置为0。 我使用Queue并递归地调用Download方法。

我尝试求和所有需要下载的字节,并将progressBar.Maximum设置为该值。但是问题在于如何使用下载的所有字节的总和来更新进度条。

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

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

    DownloadFile();
}

private void DownloadFile()
{
    if (_downloadUrls.Any())
    {
        WebClient client = new WebClient();
        client.DownloadProgressChanged += client_DownloadProgressChanged;
        client.DownloadFileCompleted += client_DownloadFileCompleted;

        var url = _downloadUrls.Dequeue();


        client.DownloadFileAsync(new Uri(url), "C:\\Test4\\" + FileName);
        return;
    }

    // End of the download
    btnGetDownload.Text = "Download Complete";
}

private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    if (e.Error != null)
    {
        // handle error scenario
        throw e.Error;
    }
    if (e.Cancelled)
    {
        // handle cancelled scenario
    }
    DownloadFile();
}

void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
   progressBar.Value = Convert.ToInt32(e.BytesReceived);
}

1 个答案:

答案 0 :(得分:0)

如前所述,对所有字节求和并将其设置为最大值。文件下载完成后,将其大小(以字节为单位)添加到字段中(例如int _downloaded)。当下载进度更改时,将进度设置为_downloaded + e.BytesReceived,即接收到的总字节数,包括过去的文件。

请注意,当您再次开始下载文件列表时,应将_downloaded重置为0。

相关问题