【发布时间】:2021-03-26 02:04:59
【问题描述】:
我真的需要一些橡皮鸭……
我有一个至少 2.3 GiB 的文件。 我目前正在将此文件下载到临时目录。 但是当下载中断(连接错误或 Windows 崩溃)时,我希望用户在它停止的地方恢复下载。并且不要重新下载整个文件。 该代码的工作原理是它继续下载文件,但我看到下载流再次从头开始。所以这意味着文件最终是(2.3 GiB + 之前下载的字节数),这会损坏我的文件。
我使用以下 sn-p 来恢复下载,所以我希望流能够恢复,它停止的地方 localStream.Seek(positionInFile, SeekOrigin.Begin);
关于我在这里缺少什么的任何想法? 这是我的代码。
BlobContainerClient containerClient = new BlobContainerClient(connectionString, container);
var blobClient = containerClient.GetBlobClient(downloadFile);
fullOutputPath = createOutputFilePath(updateFileUri.OriginalString, outputFolder);
downloadFileInfo = new FileInfo(fullOutputPath);
var response = blobClient.Download(cts.Token);
contentLength = response.Value.ContentLength;
if (contentLength.HasValue && contentLength.Value > 0)
{
if (_fileSystemService.FileExists(fullOutputPath))
{
from = downloadFileInfo.Length;
to = contentLength;
if (from == to)
{
//file is already downloaded
//skip it
progress.Report(1);
return;
}
fileMode = FileMode.Open;
positionInFile = downloadFileInfo.Length;
}
using FileStream localStream = _fileSystemService.CreateFile(fullOutputPath, fileMode, FileAccess.Write);
localStream.Seek(positionInFile, SeekOrigin.Begin);
bytesDownloaded = positionInFile;
double dprog = ((double)bytesDownloaded / (double)(contentLength.Value + positionInFile));
do
{
bytesRead = await response.Value.Content.ReadAsync(buffer, 0, buffer.Length, cts.Token);
await localStream.WriteAsync(buffer, 0, bytesRead, cts.Token);
await localStream.FlushAsync();
bytesDownloaded += bytesRead;
dprog = ((double)bytesDownloaded / (double)(contentLength.Value + positionInFile));
progress.Report(dprog);
} while (bytesRead > 0);
}
【问题讨论】:
-
你可以使用 range 分块下载
public Download(HttpRange range = default, BlobRequestConditions conditions = null, bool rangeGetContentHash = false, CancellationToken cancellationToken = default);
标签: c# azure azure-storage