Cannot download Azure Blob to stream
Asked Answered
D

1

5

I'm using Azure Blob Storage to save some files. I'm having issues downloading this stream & am not sure why. I don't get any errors, just an empty stream. I've verified that the file exists in the container, and even ran code to list all files in the container. Any help would be greatly appreciated.

private async Task<MemoryStream> GetMemoryStreamAsync(string fileName)
{
    var storageAccountName = Environment.GetEnvironmentVariable("storage_account_name");
    var storageAccountKey = Environment.GetEnvironmentVariable("storage_access_key");
    var storageContainerName = Environment.GetEnvironmentVariable("storage_container_name");

    CloudStorageAccount storageAccount = new CloudStorageAccount(new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(storageAccountName, storageAccountKey), true);
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = blobClient.GetContainerReference(storageContainerName);
    CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);

    MemoryStream stream = new MemoryStream();

    await blockBlob.DownloadToStreamAsync(stream);

    return stream;
}
Digester answered 9/10, 2018 at 20:23 Comment(3)
Depending on what the caller is doing with the stream, you might need to set the position back to zero.Paraboloid
I'm trying to pass the stream to a csv parser to enumerate the contents of the file. @EricDamtoftDigester
Yeah, in that case, you should definitely make sure to set the position on the stream back to zero so that the CSV parser can read from the beginning.Paraboloid
P
9

You'll need to set the position to zero before returning the stream so that the consumer of the stream reads it from the beginning.

MemoryStream stream = new MemoryStream();

await blockBlob.DownloadToStreamAsync(stream);

stream.Position = 0;

return stream;
Paraboloid answered 9/10, 2018 at 20:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.