从 Internet 问题 c# 取得进展和下载大文件

progress and download big files from internet problem c#

您好,我在使用此代码下载文件时遇到问题。 当我下载像 jpg 或 png 这样的小文件时,效果很好, 但是当我尝试下载像 tar、rar 或 zip 这样的大文件时 我的进度条有问题。

这是我的代码

    WebClient client;
        private void button1_Click(object sender, EventArgs e)
        {
            string url = textBox1.Text;
            if (!string.IsNullOrEmpty(url))
            {
                Thread thread = new Thread(() =>
                    {
                Uri uri = new Uri(url);
                        string filename = System.IO.Path.GetFileName(uri.AbsolutePath);
                        client.DownloadFileAsync(uri, Application.StartupPath + "/" + filename);
                });
                thread.Start();
            }
        }
and this in form load

    client = new WebClient();
            client.DownloadProgressChanged += Client_DownloadProgressChanged;
            client.DownloadFileCompleted += Client_DownloadFileCompleted;
and this is the operator

     private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            Invoke(new MethodInvoker(delegate ()
            {
                progressBar1.Minimum = 0;
                double reciverd = double.Parse(e.BytesReceived.ToString());
                double total = double.Parse(e.TotalBytesToReceive.ToString());
                double precentage = e.ProgressPercentage;
                label1.Text = $"Downloaded{string.Format("{0:0##}", precentage)}%";
                //progressBar1.Value = int.Parse(Math.Truncate(precentage).ToString());
                progressBar1.Value = (int)precentage;

                

            }));
        }

已编辑

现在进度条和下载正常,但是下载完成后进度条直接从0跳到100,看不到进度。

您只能在离散的代码行之间进行进度报告。

如果您想获得深度报告(每个文件的进度,而不是每个批次的进度),您有几个选择:

  • 找一个Class可以做这个工作,而且居然有进度汇报的Events。有些人从不 类 做
  • 对下载过程的整个内部循环进行逆向工程(保持文件请求块下载的循环)
  • 像 Windows 更新团队那样做,并意识到这实在是太麻烦了。不要打扰。

这是其中一项比它应该做的更多的工作,而且比它看起来更不值得。