WebClient.DownloadFileAsync и потеря данных (скачивание картинок с сервера) - C#

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

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

Сохраняю картинки с сервера этим способом, их от 100 до 300. Скачивается быстро, все хорошо, но некоторые файлы после завершения работы остаются пустыми..от чего это происходит и как с этим бороться ? Видимо они не успевают записаться на диск...т.к. на ssd "битых" меньше, чем на usb hdd. Очень эта проблема настораживает.
UrlList.txt - некий файл с построчными прямыми ссылками.
Листинг программы
  1. private void DownloadPhoto()
  2. {
  3. string tmp = null;
  4. string[] Urlparse = System.IO.File.ReadAllLines(pathString + "\\UrlList.txt");
  5. string[] UrlList = System.IO.File.ReadAllLines(pathString + "\\UrlList.txt");
  6. if (CountItemsTextEvent != null)
  7. CountItemsTextEvent(this, new ProcessEventArgs("Всего изображений: " + UrlList.Count()));
  8. for(int i = 0; i < UrlList.Count(); i++)
  9. {
  10. if (ProcessingLTextEvent != null)
  11. ProcessingLTextEvent(this, new ProcessEventArgs("Обработанно: " + (i + 1) + " (" + Math.Round(((Convert.ToDouble((i + 1)) / Convert.ToDouble(UrlList.Count())) * 100), 2) + "%)"));
  12. using (WebClient client = new WebClient())
  13. {
  14. Urlparse[i] = null;
  15. //System.Threading.Thread.Sleep(0300);
  16. client.DownloadFileAsync(new Uri(UrlList[i]), pathString + UrlList[i].Substring(UrlList[i].LastIndexOf('/')));
  17. Urlparse[i] = UrlList[i].Substring(UrlList[i].LastIndexOf('/'));
  18. Urlparse[i] = Urlparse[i].TrimStart('/');
  19. }
  20. }
  21. //System.Threading.Thread.Sleep(10000);
  22. if (StatusTextEvent != null)
  23. StatusTextEvent(this, new ProcessEventArgs("Статус: Перезагрузка изображений"));
  24. var dir = new DirectoryInfo(pathString);// папка с файлами
  25. foreach (FileInfo file in dir.GetFiles()) // извлекаем все файлы и кидаем их в список
  26. {
  27. FileInfo someFileInfo = new FileInfo(file.FullName);
  28. long fileByteSize = someFileInfo.Length;
  29. if (fileByteSize == 0)
  30. {
  31. for (int i = 0; i < Urlparse.Count(); i++)
  32. {
  33. if (CountItemsTextEvent != null)
  34. CountItemsTextEvent(this, new ProcessEventArgs("Всего изображений: " + i));
  35. if(file.Name == Urlparse[i])
  36. { using (WebClient client = new WebClient())
  37. {
  38. int c = 1;
  39. tmp = UrlList[i].Substring(UrlList[i].LastIndexOf('/'));
  40. tmp = tmp.TrimStart('/');
  41. client.DownloadFile(new Uri(UrlList[i]), pathString+"\\img\\"+tmp);
  42. if (ProcessingLTextEvent != null)
  43. ProcessingLTextEvent(this, new ProcessEventArgs("Обработанно: " + (c + 1) + " (" + Math.Round(((Convert.ToDouble((c + 1)) / Convert.ToDouble(i)) * 100), 2) + "%)"));
  44. }
  45. }
  46. }
  47. }
  48. }
  49. var dir_ = new DirectoryInfo(pathString+"\\img");
  50. foreach (FileInfo file in dir.GetFiles())
  51. {
  52. if (System.IO.File.Exists(pathString + "\\" + file.Name))
  53. File.Delete(pathString + "\\" + file.Name);
  54. File.Move(file.FullName, pathString);
  55. }
  56. System.IO.File.Create(pathString + "\\UrlList.txt");
  57. }
  58. }
Правда, еслждать неопределенно долго - то и асинхронный метод все загружает...

Решение задачи: «WebClient.DownloadFileAsync и потеря данных (скачивание картинок с сервера)»

textual
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Net;
  7. using System.IO;
  8.  
  9. namespace WebLoader
  10. {
  11.     public class FileLoader
  12.     {
  13.         WebClient client = new WebClient();
  14.         EventWaitHandle ready = new AutoResetEvent(false);
  15.         List<string> urlsList;
  16.  
  17.         public FileLoader(List<string> urls)
  18.         {
  19.             urlsList = urls;
  20.             client.DownloadFileCompleted += (s, e) => { ready.Set(); };
  21.             new Thread(Work).Start();
  22.         }
  23.         void Work()
  24.         {
  25.             ready.Set();
  26.  
  27.             for(int i=0; i<urlsList.Count; i++)
  28.             {
  29.                 Uri myUri = new Uri(urlsList[i]);
  30.                 client.DownloadFileAsync(myUri, string.Format("{0}{1}", Directory.GetCurrentDirectory(), "MyFile" + i + ".txt"));
  31.                 ready.WaitOne();
  32.             }
  33.         }
  34.     }
  35. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

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

15   голосов , оценка 4 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы