在C#中一次下载一个文件

时间:2014-05-02 16:59:05

标签: c# .net

我正在尝试一次下载一个文件。但是当我将我的value2添加到await Task.Delay(value2)中时;它仍然可以同时下载两个文件,而不是一次下载一个文件。请注意,我将把复选框放到我想要下载的复选框中,并且将有大约20到50次下载,我可以选择下载哪些。但主要的是如何一次下载一个而不是同时下载一个。

using System;
using System.Collections.Generic; 
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Diagnostics;


namespace DownloadFileCSharp8
{
public partial class Form1 : Form
{

    private Stopwatch workerTimeElaspsed;

    public Form1()
    {
        InitializeComponent();
    }

    private async void btnGetDownload_Click(object sender, EventArgs e)
    {
        string text = label5.Text;
        int value2;
        //value2 = value2 + 5;

        int.TryParse(text, out value2);



        InitiateDownload("http://stie.text1.txt", @"E:\Files\text1.txt", wc_DownloadFileCompleted, "text1.txt");


        await Task.Delay(value2);

        InitiateDownload("http://site.text.docx", @"E:\Files\text2.docx", wc_DownloadFileCompleted, "text2.docx");
    }

     void InitiateDownload(string RemoteAddress, string LocalFile, AsyncCompletedEventHandler CompleteCallBack, object userToken)
    {


        WebClient wc = new WebClient();
        wc.DownloadProgressChanged += wc_DownloadProgressChanged;
        wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadTimer);       
        wc.DownloadFileCompleted += wc_DownloadFileCompleted;
        wc.DownloadFileAsync(new Uri(RemoteAddress), LocalFile, userToken);



        workerTimeElaspsed = new Stopwatch();
        workerTimeElaspsed.Start();


    }

     private void DownloadTimer(object sender, DownloadProgressChangedEventArgs e)
     {


         progressBar2.Value = e.ProgressPercentage;

         if (e.ProgressPercentage > 0)
         {
             double totalTime = (100d / (double)e.ProgressPercentage) * workerTimeElaspsed.Elapsed.TotalSeconds;
             double remaining = totalTime - workerTimeElaspsed.Elapsed.TotalSeconds;
             label5.Text = Math.Round(remaining).ToString();

         }


     }

    void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
    {

        if (e.Error != null)
        {
            lblInfo1.Visible = true;
            lblInfo1.ForeColor = Color.Red;
            lblInfo1.Text = "Error Downloading ";

            //throw e.Error;
        }
        else if (e.Cancelled)
        {
            lblInfo1.Visible = true;
            lblInfo1.ForeColor = Color.Red;
            lblInfo1.Text = "Download Cancelled " + e.UserState + e.Error;
        }
        else
        {
            lblInfo1.Visible = true;
            lblInfo1.ForeColor = Color.Red;
            lblInfo1.Text = e.UserState + " Download Complete!! ";
        }
        //throw new NotImplementedException();
    }

    void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        double bytesIn = double.Parse(e.BytesReceived.ToString());
        double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
        double percentage = bytesIn / totalBytes * 100;
        progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());


    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void progressBar1_Click(object sender, EventArgs e)
    {

    }


}
}

2 个答案:

答案 0 :(得分:2)

您致电InitiateDownload开始下载,然后等待一段固定的时间(似乎很短),然后再次致电InitiateDownload开始另一次下载*,无论是否或不是第一次下载完成了。

您要做的是重新编写InitiateDownload,以便它返回Task,指示下载完成的时间。然后,您可以await该任务,并在完成后开始下一次下载。

最简单的方法是使用DownloadDataTaskAsync方法而不是DownloadFileAsync

答案 1 :(得分:0)

如果您希望它们连续发生,您需要使用DownloadFileCompleted事件来触发下一个InitiateDownload。