无法将 Blob 存储文件下载到内存流。

huangapple go评论71阅读模式
英文:

Cannot download blob storage file to memory stream

问题

我正在尝试从 Blob 存储中下载文件到流。下面的代码执行两个操作:下载到文件和下载到流,但只有下载到文件的部分有效。

var connectionString = "...";
var fileMetaData = await dbService.GetFileMetaDataAsync(fileId);
var storageAccount = CloudStorageAccount.Parse(connectionString);
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference(fileMetaData.ProjectCode);
var blobPath = "test/test.csv";
var reference = container.GetBlobReference(blobPath);
var memoryStream = new MemoryStream();
try
{
    await reference.DownloadToStreamAsync(memoryStream);
    await reference.DownloadToFileAsync("C:\\temp\\test.csv", FileMode.Create);
}
catch (RequestFailedException)
{
    logger.LogError($"无法下载 Blob:{blobPath}");
    throw;
}

当我尝试使用 StreamReader 从内存流中读取时,内存流是空的。我不太喜欢下载到临时文件然后再次读取的想法。感谢您的帮助。

英文:

I am trying to download a file from blob storage into the stream. This code below does two things: download to a file and download to stream, only the download to file part works.

            var connectionString = "..."
            var fileMetaData = await dbService.GetFileMetaDataAsync(fileId);
            var storageAccount = CloudStorageAccount.Parse(connectionString);
            var blobClient = storageAccount.CreateCloudBlobClient();
            var container = blobClient.GetContainerReference(fileMetaData.ProjectCode);
            var blobPath = $"test/test.csv";
            var reference = container.GetBlobReference(blobPath);
            var memoryStream = new MemoryStream();
            try
            {

                await reference.DownloadToStreamAsync(memoryStream);
                await reference.DownloadToFileAsync("C:\\temp\\test.csv", FileMode.Create);
            }
            catch (RequestFailedException)
            {
                logger.LogError($"Cannot download blob at {blobPath}");

                throw;
            }

The Memory stream is empty when I try to read from it with a StreamReader
I don't really like the idea of downloading to a temporary file and then read it again
Thanks for your help.

答案1

得分: 2

Using the method OpenReadAsync() solved my problem

使用方法 OpenReadAsync() 解决了我的问题

var stream = await reference.OpenReadAsync();

英文:

Using the method OpenReadAsync() solved my problem

var stream = await reference.OpenReadAsync();

huangapple
  • 本文由 发表于 2020年1月3日 21:49:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/59579729.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定