Загрузка фотографий (> 2000) через WebClient - C#

Узнай цену своей работы

Формулировка задачи:

Добрый вечер!
public async Task DownloadManyFiles(Dictionary<Uri, string> files)
{
    WebClient wc = new WebClient();
    wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
    wc.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
    foreach (KeyValuePair<Uri, string> pair in files) 
    { 
        await wc.DownloadFileTaskAsync(pair.Key, pair.Value); 
    }
    wc.Dispose();
}
 
private void ButtonSaveAll_Click(object sender, EventArgs e)
{
    Dictionary<Uri, string> dict = new Dictionary<Uri, string>();
 
    for (int i = 0; i < listPhoto.Count; i++)
    {
        Uri uri = new Uri(listPhoto[i].Split('|')[1]);
        try
        {
            dict.Add(uri, Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/folder/" + uri.Segments[4]);
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    DownloadManyFiles(dict);
Таким методом, у меня начинается скачивание файлов (фото) поочередно по прямой ссылке к фото. Так вот, иногда загрузка останавливается и всё, никаких исключений (прога не виснет). Например, встанет на 517 из 1000 и всё, дальше загрузка не идет. Все фото берутся из соц.сети вконтакте. Что это за трабла может быть? Кто сталкивался, подскажите, пожалуйста. Может можно установить какое-то

N

-ое время для начала загрузки? Пробовал на все исключения вешать

continue

, всё тщетно.

Решение задачи: «Загрузка фотографий (> 2000) через WebClient»

textual
Листинг программы
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
 
namespace vcWinFormTest {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
            btnDownload.Click += new EventHandler(btnDownload_Click);
        }
 
        void btnDownload_Click(object sender, EventArgs e) {
            Dictionary<Uri, string> addresses = new Dictionary<Uri, string>();
            foreach (string line in File.ReadAllLines("links.txt")) {
                try {
                    addresses.Add(new Uri(line), Path.GetFileName(line));
                }
                catch { }
            }
            Progress reporter = new Progress();
            reporter.ReportEvent += new EventHandler(reporter_ReportEvent);
            progressBar1.Maximum = addresses.Count;
 
            Task.Factory.StartNew(() => DownloadAllFiles(addresses, reporter));
        }
 
        void reporter_ReportEvent(object sender, EventArgs e) {
            progressBar1.Invoke((Action)(() => progressBar1.Value++));
            label1.Invoke((Action)(() => {
                label1.Text = string.Format("Downloaded: {0} from {1}",
                progressBar1.Value, progressBar1.Maximum);
            }));
            
        }
 
        public  void DownloadAllFiles(Dictionary<Uri, string> addresses, IProgress<string> reporter) {
            Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images"));
            foreach (var address in addresses) {
                string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images", address.Value);
                WebRequest req = WebRequest.Create(address.Key);
                using (WebResponse resp = req.GetResponse()) {
                    using (Stream ns = resp.GetResponseStream()) {
                        using (FileStream fs = File.Create(filePath)) {
                            ns.CopyTo(fs);
                            reporter.Report(address.Value);
                        }
                    }
                }
            }
            progressBar1.Invoke((Action)(() => progressBar1.Value = 0));
            label1.Invoke((Action)(() => label1.Text = "Completed!"));
        }
    }
    class Progress : IProgress<string> {
        public string Filename { get; private set; }
        public event EventHandler ReportEvent = delegate { };
 
        public void Report(string value) {
            Filename = value;
            ReportEvent(this, EventArgs.Empty);
        }
    }
}

Оцени полезность:

10   голосов , оценка 4.4 из 5
Похожие ответы