繁体   English   中英

为什么在使用 webclient downloadfileasync 下载文件时,progressBar 值出现异常,即它是负值?

[英]Why when downloading files using webclient downloadfileasync I'm getting exception on the progressBar value that it's negative value?

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”的值对“Value”无效。 “值”应介于“最小值”和“最大值”之间。 参数名称:值

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

我尝试添加以下行:

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

但似乎没有修复异常。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM