Skip to content

Instantly share code, notes, and snippets.

@seesharprun
Created June 30, 2020 14:48
Show Gist options
  • Save seesharprun/127428f1e1acea4be3239cf8f8622f17 to your computer and use it in GitHub Desktop.
Save seesharprun/127428f1e1acea4be3239cf8f8622f17 to your computer and use it in GitHub Desktop.
Creating & Downloading Blobs Using the Azure SDK for .NET

Creating & Downloading Blobs Using the Azure SDK for .NET

Summary

The newest Azure SDK for .NET includes include a client library that you can use to manage your Azure Blob Storage containers and blobs from C# code. In this guide, we will look at how you can get started with the latest version of this SDK.

⚠️ This guide is based on the latest version (v12) of the Azure Blob Storage client library. If you have worked with previous versions, some class and member names may have changed.

Getting the Azure.Storage.Blobs Library from NuGet

The Azure.Storage.Blobs client library is part of the Azure SDK for .NET and is available on NuGet. To install this package in your .NET project, you can use the dotnet add package command from the command line:

dotnet add package Azure.Storage.Blobs

Connecting to Azure Blob Storage

The first thing you need to do in your application code is to add two using directives for the Azure.Storage.Blobs and Azure.Storage.Blobs.Models namespaces:

using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;

Now that you are correctly referencing the SDK, you can create a new instances of the BlobServiceClient class:

BlobServiceClient client = new BlobServiceClient(connectionString);

⚠️ This class requires a string variable with the Azure Storage connection string to be injected as a constructor parameter. If you are not sure of how to find your account's connection string, refer to the Manage storage account access keys page of the Azure documentation.

Getting the Container Client

Now that you have a client that can connect to Azure Blob Storage, you can now get a client to reference a specific container.

First you will need to get an instance of the BlobContainerClient class by using the GetBlobContainerClient method of the BlobServiceClient class passing in the name of the container as a parameter:

BlobContainerClient container = client.GetBlobContainerClient("images");

Once you have your container client, you can asynchronously use the CreateIfNotExistsAsync method of the BlobContainerClient class to create the container if it doesn't already exist:

await container.CreateIfNotExistsAsync();

⚠️ Invoking the CreateIfNotExistsAsync method ensures that you never accidentally try to perform operations on a container that does not yet exist.

Now you have an instance of the container client that safely points to an existing container. This client is the key to most blob operations you wish to perform against your Azure Blob Storage account.

Enumerating Blobs in the Container

Using the container client, you can enumerate the existing blobs in the container asynchronously. To do this, we can use an asynchronous loop to iterate over the result of an invocation of the GetBlobsAsync method of the BlobContainerClient class:

await foreach (BlobItem blob in container.GetBlobsAsync())
{
    // Perform some operation
}

⚠️ Typically, enumerating multiple blobs requires you to handle multiple segmented responses from the server. Using the new await foreach feature in C# 8, you can use a simple foreach loop instead.

Within the loop, you have an instance of the BlobItem class for ever blob in your container. You can use this instance to perform operations or get metadata about each blob. For example, you can use the BlobItem.Name property to print the name of each blob:

Console.WriteLine(blob.Name);

Downloading a Blob from the Container

Manipulating blobs in a container can be done in many ways, but we will try to keep things simple by using streams in C#.

To download a blob from the container, we can start by using the GetBlobClient method of the BlobContainerClient class to reference an existing blob named header.png and store that reference in a variable of type BlobClient:

BlobClient blob = container.GetBlobClient("header.png");

Next, we need to prepare a destination to download the file. We can use the built-in System.IO.File.Create static method to create a new file named banner.png, open a modifiable stream to the newly created file, and dispose of the stream properly once we are done:

using FileStream stream = File.Create("banner.png");

⚠️ This code sample makes use of the new using declaration feature in C# 8 that will automatically dispose of the associated variable at the end of the enclosing scope.

Now that we have a blob client and a stream, we can use the DownloadToAsync method of the BlobClient class to download the contents of the blob and write the content to the stream that we pass in as a parameter:

await blob.DownloadToAsync(stream);

This effectively downloads the header.png blob, saves it to the banner.png local file, and then disposes of the in-memory objects.

Uploading a Blob to the Container

Uploading a blob is very similar to downloading a blob. The only major difference is the order in which we operate.

First, we will use the System.IO.File.OpenRead static method to create a stream with the contents of the local wallpaper.png file:

using FileStream stream = File.OpenRead("wallpaper.png");

Now, we will again use the GetBlobClient method of the BlobContainerClient class to create a reference to a blob named background.png that doesn't exist yet:

BlobClient blob = container.GetBlobClient("background.png");

Finally, we can use the UploadAsync method of the BlobClient class to take the file contents in the stream and upload it to the blob that we referenced (even if it doesn't exist yet!).

Reviewing What We Did

In these examples, we created a client that can connect to Azure Blob Storage, referenced a container, created the container if it did not exist already, listed all of the blobs in the container, downloaded a blob from the container, and then uploaded a new blob to the container.

These examples are enough to get started managing an Azure Blob Storage account from .NET using the Azure SDK. You can always go to the GitHub repo for the Azure SDK to view more examples of varying complexity.

⚠️ Want to review the sample code from this article? Check out this Gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment