How to get file from Azure storage blob in a ByteArray format using Azure.Storage.Blobs in C#
Asked Answered
E

1

16

I have a requirement to get the files from Azure storage in the byte array format using new package Azure.Storage.Blobs. I am unable to find the way to do it in a C#.

public byte[] GetFileFromAzure()
{
byte[] filebytes; 
    BlobServiceClient blobServiceClient = new BlobServiceClient( "TestClient");
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("TestContainer");
BlobClient blobClient = containerClient.GetBlobClient("te.xlsx");
    if (blobClient.ExistsAsync().Result)
{
    var response = blobClient.DownloadAsync().Result;
    using (var streamReader = new StreamReader(response.Value.Content))
    {
        var line = streamReader.ReadToEnd();
        //No idea how to convert this to ByteArray
    }
}
return filebytes;
}

Any idea how this can be achieved to get byte array of file stored on Azure blob storage?

Appreciate help.

Equivoque answered 2/12, 2020 at 21:53 Comment(4)
The blobClient has a method called DownloadToByteArray()Darmit
@DavidTansey: no there is not, there are 4 methods only, Donwload, DownloadAsync, DownloadTo, DownloadToAsyncEquivoque
I stand corrected. Thank you for that. See my answer for a suggested approach using BlobClient.DownloadTo( stream )Darmit
@DavidTansey: Yes, below code works as expected.Equivoque
D
35

Try the following to read your Blob as a stream and then convert that stream to a byte array on return:

public byte[] GetFileFromAzure()
{
    BlobServiceClient blobServiceClient = new BlobServiceClient( "TestClient");
    BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("TestContainer");
    BlobClient blobClient = containerClient.GetBlobClient("te.xlsx");
    
    if (blobClient.ExistsAsync().Result)
    {
        using (var ms = new MemoryStream())
        {
            blobClient.DownloadTo(ms);
            return ms.ToArray();
        }
    }   
    return new byte[];  // returns empty array
}
Darmit answered 2/12, 2020 at 22:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.