Download blob to a stream

Dave Gray 586 Reputation points
2023-08-10T16:03:43.4866667+00:00

Hi,

I'm writing an Azure function in C# that needs to download a .CSV to a stream.

Examples I have seen convert a BlobItem to a CloudBlockBlob but that does not work for me as I get this cast/conversion error:

User's image

Can anyone please advise on what is wrong?

My code is as follows with the error occurring on the "CloudBlockBlob blob = (CloudBlockBlob)bi;" line

Also if I'm going the wrong way about this then happy to hear of a better way :-)

I set the language to C# 4-5 times but insists that the code is PowerShell - which is obviously not correct. :-(

using Azure.Identity;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace ServiceNowDataCleanser
{
    public static class CleanIncidents
    {
        [FunctionName("CleanIncidents")]
        public static async Task<IActionResult> 
            Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] 
                HttpRequest req, ILogger log)
        {

            string storageAccountName = "MyStorageAccount";
            string containerName = "MyContainer";

            var tokenCredential = new DefaultAzureCredential();

            // Create a blob service client using the token credential
            var blobServiceClient = new 
                BlobServiceClient(new Uri($"https://{storageAccountName}.blob.core.windows.net"), tokenCredential);

            // Get a reference to the container
            var client = blobServiceClient.GetBlobContainerClient(containerName);

            var blobsList = new List<string>();


            BlobItem bi = client.GetBlobs(prefix: "incident.csv").First();
            CloudBlockBlob blob = (CloudBlockBlob)bi;
            MemoryStream stream = new MemoryStream();
            //blob.DownloadToStream(stream);

            return new OkObjectResult("Done...");
        }
    }
}

Azure Blob Storage
Azure Blob Storage
An Azure service that stores unstructured data in the cloud as blobs.
3,201 questions
Developer technologies | C#
{count} votes

1 answer

Sort by: Most helpful
  1. shiva patpi 13,366 Reputation points Microsoft Employee Moderator
    2023-08-10T20:25:12.1133333+00:00

    @Dave Gray

    I just tried below piece of code and it works perfectly , executed in local C#.net console application - it should work in the Function App environment also. Please try !!

    Only difference is , I am just looping through the blobs. I know it can be done in a better way !

       static void DownloadBlobToStream()
            {
                string connectionString = "DefaultEndpointsProtocol=https;AccountName=straccount;AccountKey=key;EndpointSuffix=core.windows.net";
                string strContainerName = "roleassignments";
                string blobPrefix = "test1.csv";
                var blobServiceClient = new BlobServiceClient(connectionString);
                var blobContainerClient = blobServiceClient.GetBlobContainerClient(strContainerName);
                foreach (BlobItem blobItem in blobContainerClient.GetBlobs(prefix: blobPrefix))
                {
                    BlobClient blobClient = blobContainerClient.GetBlobClient(blobItem.Name);
                    MemoryStream memoryStream = new MemoryStream();
                    BlobDownloadInfo blobDownloadInfo = blobClient.Download();
                    blobDownloadInfo.Content.CopyTo(memoryStream);
                    byte[] blobData = memoryStream.ToArray();
                    File.WriteAllBytes(@"c:\shiva\test2.csv", blobData);
                }
            }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.