1

如何一个一个地下载多个文件。使用我的代码。

        //Download File
    public void DownloadFile(string url, string folderfile)
    {
        WebClient wc = new WebClient();
        try
        {
            wc.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleted);
            wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadChanged);

            wc.DownloadFileAsync(new Uri(url), folderfile);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: \n\n" + ex.Message);
        }
    }

    private void DownloadChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        double bytesIn = double.Parse(e.BytesReceived.ToString());
        double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
        double percentage = bytesIn / totalBytes * 100.0;
        int percente = int.Parse(Math.Truncate(percentage).ToString());

        PBar.Value = percente;

        progress.Text = percente + " %";
        size.Text = string.Format("{0} MB / {1} MB", (e.BytesReceived / 1024d / 1024d).ToString("0.00"), (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));
    }

    private void DownloadCompleted(object sender, AsyncCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            MessageBox.Show("Erro: " + e.Error.Message);
        }
        else
        {
            info.Text = "Download Success.";
        }
    }

    public void CheckFileDownload()
    {
        string urlGame = "http://localhost/";
        string Game = "Game.exe";
        string Support = "Support.Xml";
        string Info = "Info.xml";
        if (!File.Exists(Game))
        {
            //Download Game
            DownloadFile(urlGame + Game, Game);
            info.Text = "Downloading: " + Game;

            //If the game is downloading full 
            DownloadFile(urlGame + Info, Info);
            DownloadFile(urlGame + Support, Support);
            info.Text = "Updating information...";
        }
    }

    private void Launcher_Load(object sender, EventArgs e)
    {
        CheckFileDownload();
    }

因为我需要更新检查点文件,所以在你下载游戏之后。

我看了几个主题,但没有成功。感谢所有帮助过我的人......对不起我的英语不好

感谢所有帮助我的人。我会非常感激...

4

1 回答 1

0

如果性能不是问题,您可以使用DownloadFile,然后它将按照您指定的顺序下载它们,您无需为所有重叠的异步操作而烦恼。由于您只下载 3 个文件,因此异步编码所节省的时间可能不值得。

或者,您可以为要下载的每个文件定义标志(在类级别,而不是在您的任何函数中),它可以在 Dictionary 中或仅 3 个 bool 变量中。在DownloadFilAsync 文档中,请注意 userToken 参数,您可以使用它来识别 3 个文件中的哪个文件已完成下载。使用它来设置完成的标志;然后当最后一次下载完成时,你继续接下来发生的事情。

于 2016-09-18T19:53:23.917 回答