Pollyanna
Pollyanna

Reputation: 99

Download Blob file into Memory Stream from Azure using C#

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

Upvotes: 7

Views: 21662

Answers (2)

goldenchild
goldenchild

Reputation: 21

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.

Upvotes: 2

Thiago Custodio
Thiago Custodio

Reputation: 18387

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

Upvotes: 6

Related Questions