首页 > 解决方案 > 为什么在使用 webclient downloadfileasync 下载文件时,progressBar 值为负值时出现异常?

问题描述

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

namespace DownloadFilesFromSite
{
    public partial class Form1 : Form
    {
        private Queue<string> _downloadUrls = new Queue<string>();
        private List<string> urls = new List<string>();
        private List<string> sources = new List<string>();
        private List<string> links = new List<string>();

        public Form1()
        {
            InitializeComponent();

            Sources();
        }

        private void Sources()
        {
            string link = "https://www.documentingreality.com/forum/f10/several-different-dead-chinese-women-176102/";

            for (int i = 2; i < 141; i++)
            {
                sources.Add(link + "index" + i + ".html");
            }
        }

        private void ReadSourcePage(string fn)
        {
            var lines = File.ReadAllLines(fn).ToList();

            string contains = "https://www.documentingreality.com/forum/attachments/f10/";

            for (int i = 0; i < lines.Count; i++)
            {
                if (lines[i].Contains(contains))
                {
                    int index = lines[i].IndexOf("f10/") + 4;
                    int index1 = lines[i].IndexOf(".jpg") - index;
                    string result = lines[i].Substring(index, index1);

                    links.Add(contains + result + ".jpg");
                }
            }
        }

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

            // Starts the download
            button1.Text = "Downloading...";
            button1.Enabled = false;
            progressBar1.Visible = true;
            label1.Visible = true;

            DownloadFile();
        }

        private void DownloadFile()
        {
            if (_downloadUrls.Any())
            {
                WebClient client = new WebClient();
                client.Headers.Add("User-Agent: Other");
                client.DownloadProgressChanged += client_DownloadProgressChanged;
                client.DownloadFileCompleted += client_DownloadFileCompleted;

                var url = _downloadUrls.Dequeue();
                string FileName = url.Substring(url.LastIndexOf("/") + 1,
                            (url.Length - url.LastIndexOf("/") - 1));

                client.DownloadFileAsync(new Uri(url), @"E:\dr\htmlsources\" + FileName);
                label1.Text = url;
                return;
            }

            // End of the download
            button1.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)
        {
            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 button1_Click(object sender, EventArgs e)
        {
            downloadFiles(sources);
        }
    }
}

在DownloadFile就行了:

client.DownloadFileAsync(new Uri(url), @"E:\dr\htmlsources\" + FileName);

如果我将 url 地址复制到 chrome,它将显示页面的来源,我可以保存和下载源页面,大约 700KB

但是,当它开始下载此源时单击 button1 时,它会抛出异常:

ArgumentOutOfRangeException:“-154300”的值对“值”无效。“值”应介于“最小值”和“最大值”之间。参数名称:值

如果我根本不使用progressBar1 来测试所有下载的源文件,则大约是25KB,而不是大约700KB。

我试图添加这一行:

client.Headers.Add("User-Agent: Other");

但似乎没有解决异常。

标签: c#

解决方案


DownloadFileAsync将立即返回,然后“客户端”也将超出范围。阅读如何使用 async/await 函数。


推荐阅读