Я пытаюсь загрузить большой файл с общедоступного URL-адреса. Сначала казалось, что он работает нормально, но 1/10 компьютеров, похоже, истекли. Моя первоначальная попытка состояла в том, чтобы использовать WebClient.DownloadFileAsync
, но, поскольку она никогда не завершалась, я вернулся к использованию WebRequest.Create
и напрямую читал потоки ответов.
Моя первая версия использования WebRequest.Create
обнаружила ту же проблему, что и WebClient.DownloadFileAsync
. Операция истекает, и файл не завершается.
В моей следующей версии добавлены повторные попытки, если время загрузки истекло. Вот были странности. Загрузка в конечном итоге заканчивается с 1 повторной попыткой, чтобы закончить последние 7092 байта. Таким образом, файл загружается точно такого же размера, НО файл поврежден и отличается от исходного файла. Теперь я ожидаю, что повреждение будет в последних 7092 байтах, но это не так.
Используя BeyondCompare, я обнаружил, что в поврежденном файле отсутствуют 2 фрагмента байтов, что в сумме составляет отсутствующие 7092 байта! Эти отсутствующие байты находятся в 1CA49FF0
и 1E31F380
, задолго до истечения времени загрузки и перезапуска.
Что здесь может происходить? Любые подсказки о том, как отследить эту проблему дальше?
Вот код, о котором идет речь.
public void DownloadFile(string sourceUri, string destinationPath)
{
//roughly based on: http://stackoverflow.com/questions/2269607/how-to-programmatically-download-a-large-file-in-c-sharp
//not using WebClient.DownloadFileAsync as it seems to stall out on large files rarely for unknown reasons.
using (var fileStream = File.Open(destinationPath, FileMode.Create, FileAccess.Write, FileShare.Read))
{
long totalBytesToReceive = 0;
long totalBytesReceived = 0;
int attemptCount = 0;
bool isFinished = false;
while (!isFinished)
{
attemptCount += 1;
if (attemptCount > 10)
{
throw new InvalidOperationException("Too many attempts to download. Aborting.");
}
try
{
var request = (HttpWebRequest)WebRequest.Create(sourceUri);
request.Proxy = null;//http://stackoverflow.com/questions/754333/why-is-this-webrequest-code-slow/935728#935728
_log.AddInformation("Request #{0}.", attemptCount);
//continue downloading from last attempt.
if (totalBytesReceived != 0)
{
_log.AddInformation("Request resuming with range: {0} , {1}", totalBytesReceived, totalBytesToReceive);
request.AddRange(totalBytesReceived, totalBytesToReceive);
}
using (var response = request.GetResponse())
{
_log.AddInformation("Received response. ContentLength={0} , ContentType={1}", response.ContentLength, response.ContentType);
if (totalBytesToReceive == 0)
{
totalBytesToReceive = response.ContentLength;
}
using (var responseStream = response.GetResponseStream())
{
_log.AddInformation("Beginning read of response stream.");
var buffer = new byte[4096];
int bytesRead = responseStream.Read(buffer, 0, buffer.Length);
while (bytesRead > 0)
{
fileStream.Write(buffer, 0, bytesRead);
totalBytesReceived += bytesRead;
bytesRead = responseStream.Read(buffer, 0, buffer.Length);
}
_log.AddInformation("Finished read of response stream.");
}
}
_log.AddInformation("Finished downloading file.");
isFinished = true;
}
catch (Exception ex)
{
_log.AddInformation("Response raised exception ({0}). {1}", ex.GetType(), ex.Message);
}
}
}
}
Вот вывод журнала поврежденной загрузки:
Request #1.
Received response. ContentLength=939302925 , ContentType=application/zip
Beginning read of response stream.
Response raised exception (System.Net.WebException). The operation has timed out.
Request #2.
Request resuming with range: 939295833 , 939302925
Received response. ContentLength=7092 , ContentType=application/zip
Beginning read of response stream.
Finished read of response stream.
Finished downloading file.
DownloadFile
. - person cod3monk3y   schedule 06.02.2014