给定Uris列表时,WebClient不会下载所有文件

时间:2016-06-30 00:24:13

标签: c# .net asynchronous download webclient

我正在制作一个工具,使用List<Uri>WebClient课程同时从互联网上下载图像。以下是相关代码:

我正在使用的新WebClient:

public class PatientWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
        WebRequest w = base.GetWebRequest(uri);
        w.Timeout = Timeout.Infinite;
        return w;
    }
}

和下载方法:

    public static void DownloadFiles()
    {
        string filename = string.Empty;

        while (_count < _images.Count())
        {
            PatientWebClient client = new PatientWebClient();

            client.DownloadDataCompleted += DownloadCompleted;
            filename = _images[_count].Segments.Last().ToString();
            if (!File.Exists(_destinationFolder + @"\" + filename))
            {
                try
                {
                    client.DownloadDataAsync(_images[_count], _images[_count]);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
             }
            ++_count;
        }
    }

    private static void DownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
    {
        if (e.Error == null)
        {
            Uri uri = (Uri)e.UserState;
            string saveFilename = uri.Segments.Last().ToString();

            byte[] fileData = e.Result;

            if (saveFilename.EndsWith(".jpg") || saveFilename.EndsWith(".png") || saveFilename.EndsWith(".gif"))
                using (FileStream fileStream = new FileStream(_destinationFolder + @"\" + saveFilename, FileMode.Create))
                    fileStream.Write(fileData, 0, fileData.Length);
            else
                using (FileStream fileStream = new FileStream(_destinationFolder + @"\" + saveFilename + ".jpg", FileMode.Create))
                    fileStream.Write(fileData, 0, fileData.Length);
            ++_downloadedCounter;
            ((WebClient)sender).Dispose();
        }
    }

问题是并非下载列表_images中的所有图像。如果我再次单击下载按钮,将会下载更多内容,实际上只需点击几下即可将所有内容都删除。 WebClient的超时是否超时,如果有,是否有办法让它们自动重试下载?如果没有,解决这个问题的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

我的意思是这样的,设置webclient的超时并捕获错误:

  internal class Program
  {
    private static void Main(string[] args)
    {
      Uri[] uris = {new Uri("http://www.google.com"), new Uri("http://www.yahoo.com")};
      Parallel.ForEach(uris, uri =>
      {
        using (var webClient = new MyWebClient())
        {
          try
          {
            var data = webClient.DownloadData(uri);
            // Success, do something with your data
          }
          catch (Exception ex)
          {
            // Something is wrong...
            Console.WriteLine(ex.ToString());
          }
        }
      });
    }
  }

  public class MyWebClient : WebClient
  {
    protected override WebRequest GetWebRequest(Uri uri)
    {
      var w = base.GetWebRequest(uri);
      w.Timeout = 5000; // 5 seconds timeout
      return w;
    }
  }