Download Blob file into Memory Stream from Azure using C#

Viewed 10281

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);
        }
2 Answers

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();

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.

Related