使用Web客户端DownloadFileAsync多个文件 [英] DownloadFileAsync multiple files using webclient

查看:150
本文介绍了使用Web客户端DownloadFileAsync多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说明结果
使用Web客户端的DownloadFileAsync和利用为下载URL输入的文本文件下载多个文件。

问题结果
我已经在所有使用不会下载文件的方法。刚刚运行,什么都不做。它填补则列表数组退出程序,而无需下载一个文件。我用Google搜索的解决方案,但拿出缺兵少将。然后试图搜索一个数据库中的与相同的结果中的溶液在这里。任何帮助是AP preciated。

问题搜索


  1. 为什么这个办法行不通?

  2. 我能做些什么来改善这一点,并从中学到。

code 结果
DownloadClass.cs

 使用系统;
使用System.ComponentModel;
使用System.Collections.Generic;
使用System.Net;
使用的System.Threading;
使用System.Windows.Forms的;命名空间ThreadTest
{
    类DownloadClass
    {
        公共结构下载
        {
            公共静态字符串URL {搞定;组; }
            公共静态字符串文件{搞定;组; }
            公共静态字符串[]链接;
            公共静态INT downloadcount;
        }        公共静态列表<串GT;名单=新名单,LT;串>();
        公共静态Web客户端WC =新的WebClient();        公共静态无效下载()
        {
            诠释计数= 0;
            download.URL =列表[0];
            URI URI =新的URI(download.URL);
            UriBuilder URI =新UriBuilder(URI);
            download.link = uri.Path.ToLower()斯普利特(新的char [] {'/'});            计数= 0;
            //查找文件
            的foreach(在download.link串ABS)
            {
                算上++;
                如果(abs.ToLower()。包含(HTML)|| abs.ToLower()。包含(EXE)|| abs.ToLower()。包含(TXT))
                {
                    尝试
                    {
                        download.file = download.link [统计]
                        wc.Proxy = NULL;
                        wc.DownloadFileCompleted + =新AsyncCompletedEventHandler(wc_DownloadFileCompleted);
                        wc.DownloadFileAsync(URI,Application.StartupPath +\\\\+ download.file);
                        打破;
                    }
                    赶上(例外)
                    {}
                }
            }
        }        公共静态无效BeginDownload()
        {
            新的Thread(下载)。开始();
        }        公共静态无效wc_DownloadFileCompleted(对象发件人,AsyncCompletedEventArgs E)
        {
            诠释计数= 0;
            download.downloadcount ++;
            download.URL =列表[0];
            URI URI =新的URI(download.URL);
            UriBuilder URI =新UriBuilder(URI);            download.link = uri.Path.ToLower()斯普利特(新的char [] {'/'});            计数= 0;
            //查找文件
            的foreach(在download.link串ABS)
            {
                算上++;
                如果(abs.ToLower()。包含(HTML)|| abs.ToLower()。包含(EXE)|| abs.ToLower()。包含(TXT))
                {
                    尝试
                    {
                        download.file = download.link [统计]
                    }
                    赶上(例外)
                    {}
                }
            }
            list.RemoveAt(0);
            如果(list.Count大于0)
            {
                wc.DownloadFileAsync(URI,列表[download.downloadcount] Application.StartupPath +\\\\+ download.file);
            }
            其他
            {
                Console.WriteLine(下载完成。);
                Environment.Exit(0);
            }
        }
    }
}

Program.cs中(主类)

 使用系统;
使用System.IO;
使用System.Collections.Generic;
使用System.Windows.Forms的;命名空间ThreadTest
{
    类节目
    {
        静态无效的主要(字串[] args)
        {
            如果(args.Length&。1)
            {
                Console.WriteLine(用法:{0}<下载txtfile注册表>中,Environment.GetCommandLineArgs()[0]);
                Environment.Exit(0);
            }            INT计数器= 0;
            串线;
            字符串格式=的String.Format({0} \\\\ {1},Application.StartupPath,ARGS [0]);            //逐行读取文件中的行。
            使用(StreamReader的文件=新的StreamReader(格式))
            {
                而((行= file.ReadLine())!= NULL)
                {
                    //在列表中存储的URL。
                    DownloadClass.list.Add(线);
                    反++;
                }
            }
            DownloadClass.BeginDownload();
        }
    }
}


解决方案

除了是不好的设计有很多问题,导致你的code不能(或者也不正常工作)。


  1. 您需要确保您的应用程序生命,而它下载东西。您当前的应用程序退出的时候了(你必须等待下载在你的主要完成)。

  2. 您的应用程序可能下载同一个文件多次,但都无法下载其他(您需要完全锁定的对象,当他们在一个异步=多线程的方式喜欢这里被用来访问静态对象时)BTW:不要使用静态物体不惜一切避免摆在首位。

  3. 即使2得到纠正之后,仍可能多次下载同一个文件到相同的文件名,因而失败。

只要你不知道的知识多线程

我建议你使用synchoneous方法来避免所有这些问题。

Description
Download multiple files using webclient's DownloadFileAsync and utilizing a text file for URL input for download.

Problem
The approach that I have used won't download files at all. Just runs and does nothing. It fills the list array then quits the program without downloading a single file. I have googled for solutions but come up shorthanded. Then attempted to search for a solution in the database here with same results. Any help is appreciated.

Questions

  1. Why does this approach not work?
  2. What can I do to improve this and learn from this.

Code
DownloadClass.cs

using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Windows.Forms;

namespace ThreadTest
{
    class DownloadClass
    {
        public struct download
        {
            public static string URL { get; set; }
            public static string file { get; set; }
            public static string[] link;
            public static int downloadcount;
        }

        public static List<string> list = new List<string>();
        public static WebClient wc = new WebClient();

        public static void Download()
        {
            int count = 0;
            download.URL = list[0];
            Uri URI = new Uri(download.URL);
            UriBuilder uri = new UriBuilder(URI);
            download.link = uri.Path.ToLower().Split(new char[] { '/' });

            count = 0;
            // Find file
            foreach (string abs in download.link)
            {
                count++;
                if (abs.ToLower().Contains(".html") || abs.ToLower().Contains(".exe") || abs.ToLower().Contains(".txt"))
                {
                    try
                    {
                        download.file = download.link[count];
                        wc.Proxy = null;
                        wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
                        wc.DownloadFileAsync(URI, Application.StartupPath + "\\" + download.file);
                        break;
                    }
                    catch (Exception)
                    { }
                }
            }
        }

        public static void BeginDownload()
        {
            new Thread(Download).Start();
        }

        public static void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            int count = 0;
            download.downloadcount++;
            download.URL = list[0];
            Uri URI = new Uri(download.URL);
            UriBuilder uri = new UriBuilder(URI);

            download.link = uri.Path.ToLower().Split(new char[] { '/' });

            count = 0;
            // Find file
            foreach (string abs in download.link)
            {
                count++;
                if (abs.ToLower().Contains(".html") || abs.ToLower().Contains(".exe") || abs.ToLower().Contains(".txt"))
                {
                    try
                    {
                        download.file = download.link[count];
                    }
                    catch (Exception)
                    { }
                }
            }
            list.RemoveAt(0);
            if (list.Count > 0)
            {
                wc.DownloadFileAsync(URI, list[download.downloadcount], Application.StartupPath + "\\" + download.file);
            }
            else
            {
                Console.WriteLine("Downloading is done.");
                Environment.Exit(0);
            }
        }
    }
}

Program.cs (Main Class)

using System;
using System.IO;
using System.Collections.Generic;
using System.Windows.Forms;

namespace ThreadTest
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: {0} <download txtfile>", Environment.GetCommandLineArgs()[0]);
                Environment.Exit(0);
            }

            int counter = 0;
            string line;
            string format = string.Format("{0}\\{1}", Application.StartupPath, args[0]);

            // Read the file line by line.
            using(StreamReader file = new StreamReader(format))
            {
                while ((line = file.ReadLine())!= null)
                {
                    // Store urls in a list.
                    DownloadClass.list.Add(line);
                    counter++;
                }
            }
            DownloadClass.BeginDownload();
        }
    }
}

解决方案

Besides being bad design there are lots of issues that lead to your code not (or nor correctly working).

  1. You need to make sure that you application lives while it downloads something. Your current app quits right away (you have to wait for the downloading to complete in your main).
  2. You application may download the same file multiple times but not download others at all (You need to completely lock object when they are used in an async=multithreading way like here when accessing static objects) BTW: Don't use static objects at all to avoid that in the first place.
  3. Even if 2 is corrected it may still download the same file multiple times into the same filename and thus fail.

As long as you have no knowledge about multithreading I'd recommend you use the synchoneous methods to avoid all those problems.

这篇关于使用Web客户端DownloadFileAsync多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆