Search code examples
c#.netazureazure-storageazure-blob-storage

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


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.


Solution

  • 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
    }