Using .NET SDK And Azure CLI To Access Azure Blob Storage

Using .NET SDK And Azure CLI To Access Azure Blob Storage

In this article, let’s have look at some basic concepts about Azure blobs. We will also see how to use .NET SDK with Blob storage.

What is Blob ?

Blob stands for Binary Large Object. Blob storage can be used for storing the unstructured data.

The unstructured data may include images, video files, audio files, VHDs, or even regular text / Word/ Excel/ PowerPoint files or even PDF files.

But you may have a question now.

When To Prefer Blob Storage over Azure Files ?

Azure Files is a storage service which also allows you to store the files. The file share can be accessed using HTTP / HTTPS REST APIs from anywhere in the world.

You can also store any type of files in Azure blob storage. That also can be accessed over HTTP / HTTPs from anywhere in the world.

So, the obvious query is when to use Azure Blob over Azure Files ?

Azure files also supports SMB protocol and you can mount the File Shre as a drive on your virtual machine or on premises machines.

If your application DOES NEED to access files/fas a network drive, then I guess it would make sense to use Azure Files than blob. But if it is ok to always access files on HTTP / HTTPs then you may want to choose blob storage.

Blob Storage Resources

There are three important terms here: storage account, blob containers and blobs.

Storage accounts provide unique namespace and domain name for your blob.

Inside a storage account, you can create blob containers to hold the blob data. A container organizes a set of blobs, similar to a directory in a file system. It is the top level directory for all its contents.

A storage account can include an unlimited number of containers, and a container can store an unlimited number of blobs.

Types of blobs

There are three types of blobs”

  • Block Blob: the blob type which can hold either text or binary data. Each blob is like a block and it can be managed independently.
  • Append Blob: This is similar to block blob, except it is further optimized for appending scenarios. Every blob consists of multiple blocks and append operation can append further blocks. This type is ideal for logging scenarios.
  • Page Blob: This is to store random access files. It is mainly used for storing VHD files of virtual machines.

Create Blob Storage

You need to create a storage account before creating a blob storage instance. We already have seen how to create the storage account instance in one of my previous blogs.

Creating blob storage is as easy as creating the folder.

If you are logged in to Azure Portal, you can navigate to the Azure Storage account and then select blob service. The right side panel will show a button to add containers.

When you click on + Container button, a popup will be shown for adding new container. In that popup, you can provide the blob container name and the access level.

Access level can be

  • Private – no anonymous access meaning you cannot access blob and cannot list container items anonymously. You must be a valid user to perform these operations. This is the default access level.
  • Blob – anonymous read access for blobs only meaning you can read the blob anonymously, but you cannot list the contents of blob container anonymously.
  • Container – anonymous read access for containers and blobs meaning you can list the contents of container or read the blob anonymously

Let’s keep the default access level for this demo. Provide “firstcontainer” as the name of container and click on OK. The container would be created instantly.

Blob Operations using Azure CLI

Below code shows a sample script to create the container using Azure CLI and some basic operations on blob storage.

# TO create storage account
az storage account create      \
    --name storageaccountname  \
    --resource-group SamplesRG \
    --location WestEurope      \
    --sku Standard_ZRS         \
    --encryption blob

# To export the environment variables
export AZURE_STORAGE_ACCOUNT="<account-name>"
export AZURE_STORAGE_KEY="<account-key>"

# To create the blob container
az storage container create --name sample-container

# To upload a file
az storage blob upload              \
    --container-name firstcontainer \
    --name firstfile                    \
    --file firstfile.txt

# To List contents of container
az storage blob list \
    --container-name firstcontainer \
    --output table

# To download the blob contents
az storage blob download \
    --container-name sample-container \
    --name firstfile\
    --file destination-path

# AzCopy utility to upload data to storage
azcopy --source /mnt/myfiles \
    --destination https://<account>.blob.core.windows.net/firstcontainer \
    --dest-key <account-key> \
    --include "firstfile.txt"

Blob Operations Using .NET SDK

.NET SDK is available in two versions as of now – v11 and v12. Below steps are useful if you want to use v12 SDK.

The steps for v11 are also almost same, the package name is different. It is Microsoft.Azure.Storage.Blob.

Below are the important classes which we are going to use in this section:

Use the following .NET classes to interact with these resources:

For using .NET SDK, below are the steps:

  • Get connection string of Azure blob
  • Create the .NET project / solution
  • Add reference to NuGet package Azure.Storage.Blobs
  • Perform operations like create container, upload/download blob, etc.

Get Connection String

Sign in to Azure Portal and navigate to storage account. In the Settings section of the storage account overview, select Access keys.

Here, you can view the account keys and the complete connection string for each key. Find the connection string under any key (let’s say Key 1).

Add NuGet Package

For installing NuGet package, you can add reference to the NuGet package using Add Reference.

Alternatively, you can execute below command on NuGet Package Manager console.

Install-Package Azure.Storage.Blobs

C# Code

The BlobServiceClient object can be used to connect with Blob service. Below code calls CreateBlobContainerAsync method to create a new container with specified name.

var blobServiceClient = new BlobServiceClient(connectionString);
var containerName = "<some-unique-name>";
var containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);

You can get reference to new container by using GetBlobClient method of BlobContainerClient. Then you can use stream to upload the file to the blob container as shown in below code.

// Get a reference to a blob
BlobClient blobClient = containerClient.GetBlobClient(fileName);

// Open the file and upload its data
using FileStream uploadFileStream = File.OpenRead(fileName);

// Upload the file
await blobClient.UploadAsync(uploadFileStream);

// Close the stream
uploadFileStream.Close();

Below code is to list all blobs from the container.

// List all blobs in container
await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
{
    Console.WriteLine("\t" + blobItem.Name);
}

The BlobDownloadInfo can be used to download the file as shown in below code.

// Download the blob's contents and save it to a file
var download = await blobClient.DownloadAsync();

using FileStream downloadFileStream = File.OpenWrite(downloadFilePath);
await download.Content.CopyToAsync(downloadFileStream);
downloadFileStream.Close();

To delete the container, you can just call delete method on the blob container.

await containerClient.DeleteAsync();

I hope this helps to get started on Azure Blob storage. Let me know your thoughts.

Leave a Reply