Read blob file from Microsoft Azure Storage with .NET Core

UPDATE 2021-06-29: Microsoft have change the approach to storage accounts. Read the new way here: Read and Write blob file from Microsoft Azure Storage with .NET Core.

In order to read a blob file from a Microsoft Azure Blob Storage, you need to know the following:

  • The storage account connection string. This is the long string that looks like this:
    DefaultEndpointsProtocol=https;
    AccountName=someaccounfname;
    AccountKey=AVeryLongCrypticalStringThatContainsALotOfChars==
  • The blob storage container name. This is the name in the list of “Blobs”.
  • The blob file name. This is the name of the blob inside the container. A file name can be in form of a path, as blobs are structured as a file structure inside the container. For ecample: folder/folder/file.extension

You also need this NuGet package:

Windows.Azure.Storage

The code is pretty simple:

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;

public string GetBlob(string containerName, string fileName)
{
  string connectionString = $"yourconnectionstring";

  // Setup the connection to the storage account
  CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

  // Connect to the blob storage
  CloudBlobClient serviceClient = storageAccount.CreateCloudBlobClient();
  // Connect to the blob container
  CloudBlobContainer container = serviceClient.GetContainerReference($"{containerName}");
  // Connect to the blob file
  CloudBlockBlob blob = container.GetBlockBlobReference($"{fileName}");
  // Get the blob file as text
  string contents = blob.DownloadTextAsync().Result;

  return contents;
}

The usage is equally easy:

GetBlob("containername", "my/file.json");

MORE TO READ:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .NET Core, Microsoft Azure and tagged , . Bookmark the permalink.

6 Responses to Read blob file from Microsoft Azure Storage with .NET Core

  1. Steven Gibson says:

    Thanks for this small piece of instruction. Helped me out a lot.

    Like

  2. Pierpaolo Francocci says:

    please … how to write json in a container ? how to SetBlob?

    Like

  3. Pingback: Read and Write blob file from Microsoft Azure Storage with .NET Core | Brian Pedersen's Sitecore and .NET Blog

  4. briancaos says:

    There is a new approach to blobs. See here how it’s done:

    Read and Write blob file from Microsoft Azure Storage with .NET Core

    Like

  5. Pingback: Read blob file from Microsoft Azure Storage with .NET Core - 365 Community

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.