Download Blob file into Memory Stream from Azure using C#
Asked Answered
A

2

7

I am trying to read a blob from Azure using C# Console application. I can download the blob file to my local machine and read it but when I am trying to download it to memory stream it is throwing an error as attached.enter image description here

I want to directly read my blob file instead of downloading it to local machine as I have to deploy it in Azure. Any suggestions on it?

var storageaccount = new CloudStorageAccount(new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(StorageAccountName, StorageAccountKey), true);
        var blobclient = storageaccount.CreateCloudBlobClient();
        var container = blobclient.GetContainerReference("");
       // var blobs = container.ListBlobs();
       var blockBlobReference = container.GetBlockBlobReference(sourceBlobFileName);
        using (var memorystream = new MemoryStream())
        {
            blockBlobReference.DownloadToStream(memorystream);
        }
Acoustician answered 23/6, 2020 at 16:54 Comment(0)
B
6

I think the problem is because you're wrapping it in a using statement. Try the following:

var storageaccount = new CloudStorageAccount(new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(StorageAccountName, StorageAccountKey), true);
var blobclient = storageaccount.CreateCloudBlobClient();
var container = blobclient.GetContainerReference("");
// var blobs = container.ListBlobs();
var blockBlobReference = container.GetBlockBlobReference(sourceBlobFileName);
var memorystream = new MemoryStream();

blockBlobReference.DownloadToStream(memorystream);
byte[] content = memoryStream.ToArray();
Buoyant answered 23/6, 2020 at 17:43 Comment(0)
E
2

I tried your code, but Blob downloaded successfully.

your screenshot just shows the variable in Visual Studio debugger, and it looks like the error doesn't actually occurred.

In screenshot, MemoryStream, CanTimeout property set to false. So, it seems that ReadTimeout and WriteTimeout throw exceptions only because MemoryStream does not support them.

Reference:

Please note that the exception won't occurred until you use ReadTimeout and WriteTimeout properties.

Expurgatory answered 23/6, 2020 at 19:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.