WebClient.DownloadFileAsync и потеря данных (скачивание картинок с сервера) - C#
Формулировка задачи:
Сохраняю картинки с сервера этим способом, их от 100 до 300. Скачивается быстро, все хорошо, но некоторые файлы после завершения работы остаются пустыми..от чего это происходит и как с этим бороться ? Видимо они не успевают записаться на диск...т.к. на ssd "битых" меньше, чем на usb hdd. Очень эта проблема настораживает.
Правда, еслждать неопределенно долго - то и асинхронный метод все загружает...
UrlList.txt - некий файл с построчными прямыми ссылками.
private void DownloadPhoto()
{
string tmp = null;
string[] Urlparse = System.IO.File.ReadAllLines(pathString + "\\UrlList.txt");
string[] UrlList = System.IO.File.ReadAllLines(pathString + "\\UrlList.txt");
if (CountItemsTextEvent != null)
CountItemsTextEvent(this, new ProcessEventArgs("Всего изображений: " + UrlList.Count()));
for(int i = 0; i < UrlList.Count(); i++)
{
if (ProcessingLTextEvent != null)
ProcessingLTextEvent(this, new ProcessEventArgs("Обработанно: " + (i + 1) + " (" + Math.Round(((Convert.ToDouble((i + 1)) / Convert.ToDouble(UrlList.Count())) * 100), 2) + "%)"));
using (WebClient client = new WebClient())
{
Urlparse[i] = null;
//System.Threading.Thread.Sleep(0300);
client.DownloadFileAsync(new Uri(UrlList[i]), pathString + UrlList[i].Substring(UrlList[i].LastIndexOf('/')));
Urlparse[i] = UrlList[i].Substring(UrlList[i].LastIndexOf('/'));
Urlparse[i] = Urlparse[i].TrimStart('/');
}
}
//System.Threading.Thread.Sleep(10000);
if (StatusTextEvent != null)
StatusTextEvent(this, new ProcessEventArgs("Статус: Перезагрузка изображений"));
var dir = new DirectoryInfo(pathString);// папка с файлами
foreach (FileInfo file in dir.GetFiles()) // извлекаем все файлы и кидаем их в список
{
FileInfo someFileInfo = new FileInfo(file.FullName);
long fileByteSize = someFileInfo.Length;
if (fileByteSize == 0)
{
for (int i = 0; i < Urlparse.Count(); i++)
{
if (CountItemsTextEvent != null)
CountItemsTextEvent(this, new ProcessEventArgs("Всего изображений: " + i));
if(file.Name == Urlparse[i])
{ using (WebClient client = new WebClient())
{
int c = 1;
tmp = UrlList[i].Substring(UrlList[i].LastIndexOf('/'));
tmp = tmp.TrimStart('/');
client.DownloadFile(new Uri(UrlList[i]), pathString+"\\img\\"+tmp);
if (ProcessingLTextEvent != null)
ProcessingLTextEvent(this, new ProcessEventArgs("Обработанно: " + (c + 1) + " (" + Math.Round(((Convert.ToDouble((c + 1)) / Convert.ToDouble(i)) * 100), 2) + "%)"));
}
}
}
}
}
var dir_ = new DirectoryInfo(pathString+"\\img");
foreach (FileInfo file in dir.GetFiles())
{
if (System.IO.File.Exists(pathString + "\\" + file.Name))
File.Delete(pathString + "\\" + file.Name);
File.Move(file.FullName, pathString);
}
System.IO.File.Create(pathString + "\\UrlList.txt");
}
}Решение задачи: «WebClient.DownloadFileAsync и потеря данных (скачивание картинок с сервера)»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.IO;
namespace WebLoader
{
public class FileLoader
{
WebClient client = new WebClient();
EventWaitHandle ready = new AutoResetEvent(false);
List<string> urlsList;
public FileLoader(List<string> urls)
{
urlsList = urls;
client.DownloadFileCompleted += (s, e) => { ready.Set(); };
new Thread(Work).Start();
}
void Work()
{
ready.Set();
for(int i=0; i<urlsList.Count; i++)
{
Uri myUri = new Uri(urlsList[i]);
client.DownloadFileAsync(myUri, string.Format("{0}{1}", Directory.GetCurrentDirectory(), "MyFile" + i + ".txt"));
ready.WaitOne();
}
}
}
}