我从下面的代码中得到一个错误。 在我的自定义 DownloadFile 方法中出现错误 416 Requested Range Not Satisfiable。 我的文件是一个带有两个 pdf 的 zip 文件。此代码仅针对该特定文件中断。我有 55 个文件,其中只有一个文件给我这个错误。文件正在从 Azure 网站目录上传/下载。
查看该文件下面的属性窗口:
这是我的代码:
try
{
var packageId = updates[0];
var packagePath = updates[1];
var packageNameAvailable = Path.GetFileName(updates[1]);
log.Info($"Package id {packageId} | {packageNameAvailable} is available to download. ");
DownloadPackagePath = string.Format(@"{0}\{1}", ApiConfigHelper.PackageRootDirectory, packageNameAvailable);
var url = new Uri(updates[1]);
**DownloadFile(url.OriginalString, DownloadPackagePath);** // problem here
result = true;
}
catch (Exception ex)
{
log.Info("Error occurred while downloading package, stopping download. Cleaning up resources. ");
log.Error($"Error:{ex.Message}", ex);
log.Info("Cleaning up started....");
result = false;
}
下载文件方法:
private void DownloadFile(string sourceURL, string destinationPath)
{
long fileSize = 0;
int bufferSize = 1024;
bufferSize *= 1000;
long existLen = 0;
FileStream saveFileStream = null;
Stream resStream = null;
try
{
log.Info("Download started....");
if (File.Exists(destinationPath))
{
FileInfo destinationFileInfo = new FileInfo(destinationPath);
existLen = destinationFileInfo.Length;
log.Info($"Resuming partial downloaded file from {existLen / 1024} kB started....");
}
if (existLen > 0)
{
saveFileStream = new FileStream(destinationPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
}
else
{
saveFileStream = new FileStream(destinationPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
FileInfo destinationFileInfo = new FileInfo(destinationPath);
log.Info($"Starting download FileName:{destinationFileInfo.Name} Size: {destinationFileInfo.Length / 1024} kB ....");
}
var httpRequest = (HttpWebRequest)WebRequest.Create(sourceURL);
httpRequest.AddRange((int)existLen);
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
resStream = httpResponse.GetResponseStream();
fileSize = httpResponse.ContentLength;
int byteSize;
byte[] downBuffer = new byte[bufferSize];
while ((byteSize = resStream.Read(downBuffer, 0, downBuffer.Length)) > 0)
{
saveFileStream.Write(downBuffer, 0, byteSize);
}
log.Info("File downloaded successfully. Clean up started....");
}
catch
{
throw;
}
finally
{
log.Info("Cleaning up unused streams....");
if (saveFileStream != null)
{
saveFileStream.Close();
saveFileStream.Dispose();
}
if (resStream != null)
{
resStream.Close();
resStream.Dispose();
}
log.Info("DONE!!!");
}
}
你能帮我识别一下吗。我的日志中有一个条目说 从 2494 kB 开始恢复部分下载的文件.... 并且只坚持这一点。
最佳答案
Resuming partial downloaded file from 2494 kB started
根据日志信息,请求范围从2494 * 1024(2553856)开始。 2,553,856 字节大于从文件属性窗口中可以看到的文件大小(2,492,548)。您请求的文件范围不存在会导致416(Requested Range Not Satisfiable)错误。
原因可能是存在文件。它与您要下载的 zip 文件同名。尝试删除同一文件夹中的现有文件将解决此问题。
关于c# - 错误 416 请求的范围在 c# 中不可满足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42629129/