为什么在单击开始按钮时再次尝试下载文件时,进度栏出现异常?

时间:2018-10-12 17:29:41

标签: c# winforms

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.IO;
using System.Net;
using System.Xml.Linq;
using System.Diagnostics;
using System.Management;
using System.Runtime.InteropServices;

namespace DownloadFiles
{
    public partial class Form1 : Form
    {
        Stopwatch sw = new Stopwatch();
        Stopwatch stopwatch = new Stopwatch();
        string filesdirectory = "Downloaded_Files";
        string mainurl = "http://www.usgodae.org/ftp/outgoing/fnmoc/models/navgem_0.5/latest_data/";
        List<string> parsedlinks = new List<string>();
        string path_exe = Path.GetDirectoryName(Application.LocalUserAppDataPath);
        List<string> results = new List<string>();
        List<string> urls = new List<string>();
        string radarImageWebAddressP1;
        string radarImageWebAddressP2;

        public Form1()
        {
            InitializeComponent();

            label3.Text = "";
            label4.Text = "";
            label5.Text = "";
            label7.Text = "";
            button2.Enabled = false;
            button3.Enabled = false;
            filesdirectory = Path.Combine(path_exe, filesdirectory);
            if (!Directory.Exists(filesdirectory))
            {
                Directory.CreateDirectory(filesdirectory);
            }
            else
            {
                if (IsDirectoryEmpty(filesdirectory) == false)
                {
                    button3.Enabled = true;
                }
            }

            radarImageWebAddressP1 = "http://www.ims.gov.il/Ims/Pages/RadarImage.aspx?Row=";
            radarImageWebAddressP2 = "&TotalImages=10&LangID=1&Location=";

            for (int i = 0; i < 9; i++)
            {
                urls.Add(radarImageWebAddressP1 + i + radarImageWebAddressP2);
            }
        }

        public bool IsDirectoryEmpty(string path)
        {
            return !Directory.EnumerateFileSystemEntries(path).Any();
        }

        private string downloadhtml(string url)
        {
            backgroundWorker1.ReportProgress(0, "Downloading Main Url");
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Proxy = null;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream());
            string html = sr.ReadToEnd();
            sr.Close();
            response.Close();
            StreamWriter w = new StreamWriter(path_exe + "\\page.html");
            w.Write(html);
            w.Close();
            return html;
        }

        int Counter = 0;
        int percentage = 0;
        int total = 0;
        int countfiletodownload = 0;
        bool processStatus = false;
        private void Parseanddownloadfiles()
        {
            //downloadhtml(mainurl);
            if (bgw.CancellationPending == false)
            {
                /*backgroundWorker1.ReportProgress(0, "Parsing Links");
                HtmlAgilityPack.HtmlWeb hw = new HtmlAgilityPack.HtmlWeb();
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc = hw.Load(path_exe + "\\page.html");
                foreach (HtmlAgilityPack.HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
                {
                    string hrefValue = link.GetAttributeValue("href", string.Empty);
                    if (hrefValue.Contains("US"))
                    {
                        string url = "http://www.usgodae.org/ftp/outgoing/fnmoc/models/navgem_0.5/latest_data/" + hrefValue;
                        parsedlinks.Add(url);
                        if (bgw.CancellationPending == true)
                            return;
                    }
                }*/
                parsedlinks = urls;
                countfiletodownload = parsedlinks.Count;
                total = parsedlinks.Count;
                backgroundWorker1.ReportProgress(0, "Downloading Files");
                processStatus = true;
                for (int i = 0; i < parsedlinks.Count && bgw.CancellationPending == false; i++)
                {
                    try
                    {
                        using (WebClient client = new WebClient())
                        {
                            sw.Start();
                            Uri uri = new Uri(parsedlinks[i]);
                            string filename = "RadarImage" + i.ToString() + ".gif";//parsedlinks[i].Substring(71);
                            client.DownloadFileAsync(uri, filesdirectory + "\\" + filename);
                            Counter += 1;
                            percentage = Counter * 100 / total;
                            string filenametoreport = filename.Substring(1);
                            countfiletodownload--;
                            backgroundWorker1.ReportProgress(percentage, filenametoreport);//countfiletodownload, filenametoreport);
                        }
                    }
                    catch (Exception err)
                    {
                        string error = err.ToString();
                    }
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        BackgroundWorker bgw;
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            bgw = (BackgroundWorker)sender;
            if (bgw.CancellationPending == true)
            {
                return;
            }
            else
            {
                Parseanddownloadfiles();
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.UserState.ToString() == "Downloading Main Url")
            {
                label3.Text = e.UserState.ToString();
            }
            if (e.UserState.ToString() == "Parsing Links")
            {
                label3.Text = e.UserState.ToString();
            }
            if (e.UserState.ToString() == "Downloading Files")
            {
                label7.Text = countfiletodownload.ToString();//parsedlinks.Count.ToString();
                label3.Text = e.UserState.ToString();
            }
            if (processStatus == true)
            {
                if (e.UserState.ToString() != "Downloading Files")
                {
                    label4.Text = e.UserState.ToString();
                    label7.Text = countfiletodownload.ToString();
                    progressBar1.Value = e.ProgressPercentage;
                    /*using (var bitmap = new Bitmap(this.Width, this.Height))
                    {
                        this.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
                        bitmap.Save(@"e:\screens\ss.gif" + countscreenshots, System.Drawing.Imaging.ImageFormat.Gif);
                        countscreenshots += 1;
                    }*/
                }
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
            }
            else
            {
                label3.Text = "Download Completed";
                stopwatch.Reset();
                stopwatch.Stop();
                timer1.Stop();
            }
            if(e.Cancelled)
                label3.Text = "Operation Cancelled";

            button1.Enabled = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            label3.Text = "Cancelling Operation";
            backgroundWorker1.CancelAsync();
            button2.Enabled = false;
            timer1.Stop();
            stopwatch.Stop();
            stopwatch.Reset();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label3.Text = "";
            label4.Text = "";
            label7.Text = "";
            backgroundWorker1.RunWorkerAsync();
            timer1.Start();
            stopwatch.Start();
            button1.Enabled = false;
            button2.Enabled = true;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Process.Start(filesdirectory);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label5.Text = string.Format("{0:hh\\:mm\\:ss}", stopwatch.Elapsed);
        }
    }
}

第一次下载正常,但是下次再次单击开始按钮(button1)时,它显示异常:System.Reflection.TargetInvocationException:'异常已被调用的目标抛出。'

我试图在开始按钮(button1)click事件中将progressBar值重置为0,但是并不能解决问题。

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

1 个答案:

答案 0 :(得分:2)

ArgumentOutOfRange异常是因为您从未重置Counter

您将Counter定义为类级别变量,并将其初始化为0:

int Counter = 0;

然后在您的循环中调用:

Counter += 1;
percentage = Counter * 100 / total;

单击按钮重新开始下载时,Counter仍保留上一次运行的最终值。

button1_Click中,先于RunWorkerAsync

您需要重置它:

Counter = 0;