Quickstart: Azure Blob Storage client library for .NET

Get started with the Azure Blob Storage client library for .NET. Azure Blob Storage is Microsoft's object storage solution for the cloud. Follow these steps to install the package and try out example code for basic tasks. Blob storage is optimized for storing massive amounts of unstructured data.

API reference documentation | Library source code | Package (NuGet) | Samples

Prerequisites

Setting up

This section walks you through preparing a project to work with the Azure Blob Storage client library for .NET.

Create the project

For the steps ahead, you'll need to create a .NET console app using either the .NET CLI or Visual Studio 2022.

  1. At the top of Visual Studio, navigate to File > New > Project...

  2. In the dialog window, enter console app into the project template search box and select the first result. Choose Next at the bottom of the dialog.

    A screenshot showing how to create a new project using Visual Studio.

  3. For the Project Name, enter BlobQuickstart. Leave the default values for the rest of the fields and select Next.

  4. For the Framework, ensure .NET 6.0 is selected. Then choose Create. The new project will open inside the Visual Studio environment.

Install the package

To interact with Azure Blob Storage, install the Azure Blob Storage client library for .NET.

  1. In Solution Explorer, right-click the Dependencies node of your project. Select Manage NuGet Packages.

  2. In the resulting window, search for Azure.Storage.Blobs. Select the appropriate result, and select Install.

    A screenshot showing how to add a new package using Visual Studio.

Set up the app code

Replace the starting code in the Program.cs file so that it matches the following example, which includes the necessary using statements for this exercise.

using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using System;
using System.IO;

// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

Authenticate to Azure and authorize access to blob data

Application requests to Azure Blob Storage must be authorized. Using the DefaultAzureCredential class provided by the Azure Identity client library is the recommended approach for implementing passwordless connections to Azure services in your code, including Blob Storage.

You can also authorize requests to Azure Blob Storage by using the account access key. However, this approach should be used with caution. Developers must be diligent to never expose the access key in an unsecure location. Anyone who has the access key is able to authorize requests against the storage account, and effectively has access to all the data. DefaultAzureCredential offers improved management and security benefits over the account key to allow passwordless authentication. Both options are demonstrated in the following example.

DefaultAzureCredential is a class provided by the Azure Identity client library for .NET, which you can learn more about on the DefaultAzureCredential overview. DefaultAzureCredential supports multiple authentication methods and determines which method should be used at runtime. This approach enables your app to use different authentication methods in different environments (local vs. production) without implementing environment-specific code.

The order and locations in which DefaultAzureCredential looks for credentials can be found in the Azure Identity library overview.

For example, your app can authenticate using your Visual Studio sign-in credentials with when developing locally. Your app can then use a managed identity once it has been deployed to Azure. No code changes are required for this transition.

Assign roles to your Azure AD user account

When developing locally, make sure that the user account that is accessing blob data has the correct permissions. You'll need Storage Blob Data Contributor to read and write blob data. To assign yourself this role, you'll need to be assigned the User Access Administrator role, or another role that includes the Microsoft.Authorization/roleAssignments/write action. You can assign Azure RBAC roles to a user using the Azure portal, Azure CLI, or Azure PowerShell. You can learn more about the available scopes for role assignments on the scope overview page.

In this scenario, you'll assign permissions to your user account, scoped to the storage account, to follow the Principle of Least Privilege. This practice gives users only the minimum permissions needed and creates more secure production environments.

The following example will assign the Storage Blob Data Contributor role to your user account, which provides both read and write access to blob data in your storage account.

Important

In most cases it will take a minute or two for the role assignment to propagate in Azure, but in rare cases it may take up to eight minutes. If you receive authentication errors when you first run your code, wait a few moments and try again.

  1. In the Azure portal, locate your storage account using the main search bar or left navigation.

  2. On the storage account overview page, select Access control (IAM) from the left-hand menu.

  3. On the Access control (IAM) page, select the Role assignments tab.

  4. Select + Add from the top menu and then Add role assignment from the resulting drop-down menu.

    A screenshot showing how to assign a role.

  5. Use the search box to filter the results to the desired role. For this example, search for Storage Blob Data Contributor and select the matching result and then choose Next.

  6. Under Assign access to, select User, group, or service principal, and then choose + Select members.

  7. In the dialog, search for your Azure AD username (usually your user@domain email address) and then choose Select at the bottom of the dialog.

  8. Select Review + assign to go to the final page, and then Review + assign again to complete the process.

Sign-in and connect your app code to Azure using DefaultAzureCredential

You can authorize access to data in your storage account using the following steps:

  1. Make sure you're authenticated with the same Azure AD account you assigned the role to. You can authenticate via the Azure CLI, Visual Studio, or Azure PowerShell.

    Sign-in to Azure through the Azure CLI using the following command:

    az login
    
  2. To use DefaultAzureCredential, add the Azure.Identity package to your application.

    1. In Solution Explorer, right-click the Dependencies node of your project. Select Manage NuGet Packages.

    2. In the resulting window, search for Azure.Identity. Select the appropriate result, and select Install.

      A screenshot showing how to add the identity package.

  3. Update your Program.cs code to match the following example. When the code is run on your local workstation during development, it will use the developer credentials of the prioritized tool you're logged into to authenticate to Azure, such as the Azure CLI or Visual Studio.

    using Azure.Storage.Blobs;
    using Azure.Storage.Blobs.Models;
    using System;
    using System.IO;
    using Azure.Identity;
    
    // TODO: Replace <storage-account-name> with your actual storage account name
    var blobServiceClient = new BlobServiceClient(
            new Uri("https://<storage-account-name>.blob.core.windows.net"),
            new DefaultAzureCredential());
    
  4. Make sure to update the storage account name in the URI of your BlobServiceClient. The storage account name can be found on the overview page of the Azure portal.

    A screenshot showing how to find the storage account name.

    Note

    When deployed to Azure, this same code can be used to authorize requests to Azure Storage from an application running in Azure. However, you'll need to enable managed identity on your app in Azure. Then configure your storage account to allow that managed identity to connect. For detailed instructions on configuring this connection between Azure services, see the Auth from Azure-hosted apps tutorial.

Object model

Azure Blob Storage is optimized for storing massive amounts of unstructured data. Unstructured data doesn't adhere to a particular data model or definition, such as text or binary data. Blob storage offers three types of resources:

  • The storage account
  • A container in the storage account
  • A blob in the container

The following diagram shows the relationship between these resources.

Diagram of Blob storage architecture.

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

  • BlobServiceClient: The BlobServiceClient class allows you to manipulate Azure Storage resources and blob containers.
  • BlobContainerClient: The BlobContainerClient class allows you to manipulate Azure Storage containers and their blobs.
  • BlobClient: The BlobClient class allows you to manipulate Azure Storage blobs.

Code examples

The sample code snippets in the following sections demonstrate how to perform basic data operations with the Azure Blob Storage client library for .NET.

Important

Make sure you have installed the correct NuGet packages and added the necessary using statements in order for the code samples to work, as described in the setting up section.

  • Azure.Identity (if you are using the passwordless approach)
  • Azure.Storage.Blobs

Create a container

Decide on a name for the new container. The code below appends a GUID value to the container name to ensure that it is unique.

Important

Container names must be lowercase. For more information about naming containers and blobs, see Naming and Referencing Containers, Blobs, and Metadata.

You can call the CreateBlobContainerAsync method on the blobServiceClient to create a container in your storage account.

Add this code to the end of the Program.cs class:

// TODO: Replace <storage-account-name> with your actual storage account name
var blobServiceClient = new BlobServiceClient(
        new Uri("https://<storage-account-name>.blob.core.windows.net"),
        new DefaultAzureCredential());

//Create a unique name for the container
string containerName = "quickstartblobs" + Guid.NewGuid().ToString();

// Create the container and return a container client object
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);

Upload a blob to a container

Add the following code to the end of the Program.cs class:

// Create a local file in the ./data/ directory for uploading and downloading
string localPath = "data";
Directory.CreateDirectory(localPath);
string fileName = "quickstart" + Guid.NewGuid().ToString() + ".txt";
string localFilePath = Path.Combine(localPath, fileName);

// Write text to the file
await File.WriteAllTextAsync(localFilePath, "Hello, World!");

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

Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);

// Upload data from the local file
await blobClient.UploadAsync(localFilePath, true);

The code snippet completes the following steps:

  1. Creates a text file in the local data directory.
  2. Gets a reference to a BlobClient object by calling the GetBlobClient method on the container from the Create a container section.
  3. Uploads the local text file to the blob by calling the UploadAsync method. This method creates the blob if it doesn't already exist, and overwrites it if it does.

List blobs in a container

List the blobs in the container by calling the GetBlobsAsync method. In this case, only one blob has been added to the container, so the listing operation returns just that one blob.

Add the following code to the end of the Program.cs class:

Console.WriteLine("Listing blobs...");

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

Download a blob

Download the previously created blob by calling the DownloadToAsync method. The example code adds a suffix of "DOWNLOADED" to the file name so that you can see both files in local file system.

Add the following code to the end of the Program.cs class:

// Download the blob to a local file
// Append the string "DOWNLOADED" before the .txt extension 
// so you can compare the files in the data directory
string downloadFilePath = localFilePath.Replace(".txt", "DOWNLOADED.txt");

Console.WriteLine("\nDownloading blob to\n\t{0}\n", downloadFilePath);

// Download the blob's contents and save it to a file
await blobClient.DownloadToAsync(downloadFilePath);

Delete a container

The following code cleans up the resources the app created by deleting the entire container by using DeleteAsync. It also deletes the local files created by the app.

The app pauses for user input by calling Console.ReadLine before it deletes the blob, container, and local files. This is a good chance to verify that the resources were actually created correctly, before they are deleted.

Add the following code to the end of the Program.cs class:

// Clean up
Console.Write("Press any key to begin clean up");
Console.ReadLine();

Console.WriteLine("Deleting blob container...");
await containerClient.DeleteAsync();

Console.WriteLine("Deleting the local source and downloaded files...");
File.Delete(localFilePath);
File.Delete(downloadFilePath);

Console.WriteLine("Done");

The completed code

After completing these steps the code in your Program.cs file should now resemble the following:

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

// TODO: Replace <storage-account-name> with your actual storage account name
var blobServiceClient = new BlobServiceClient(
        new Uri("https://<storage-account-name>.blob.core.windows.net"),
        new DefaultAzureCredential());

//Create a unique name for the container
string containerName = "quickstartblobs" + Guid.NewGuid().ToString();

// Create the container and return a container client object
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);

// Create a local file in the ./data/ directory for uploading and downloading
string localPath = "data";
Directory.CreateDirectory(localPath);
string fileName = "quickstart" + Guid.NewGuid().ToString() + ".txt";
string localFilePath = Path.Combine(localPath, fileName);

// Write text to the file
await File.WriteAllTextAsync(localFilePath, "Hello, World!");

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

Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);

// Upload data from the local file
await blobClient.UploadAsync(localFilePath, true);

Console.WriteLine("Listing blobs...");

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

// Download the blob to a local file
// Append the string "DOWNLOADED" before the .txt extension 
// so you can compare the files in the data directory
string downloadFilePath = localFilePath.Replace(".txt", "DOWNLOADED.txt");

Console.WriteLine("\nDownloading blob to\n\t{0}\n", downloadFilePath);

// Download the blob's contents and save it to a file
await blobClient.DownloadToAsync(downloadFilePath);

// Clean up
Console.Write("Press any key to begin clean up");
Console.ReadLine();

Console.WriteLine("Deleting blob container...");
await containerClient.DeleteAsync();

Console.WriteLine("Deleting the local source and downloaded files...");
File.Delete(localFilePath);
File.Delete(downloadFilePath);

Console.WriteLine("Done");

Run the code

This app creates a test file in your local data folder and uploads it to Blob storage. The example then lists the blobs in the container and downloads the file with a new name so that you can compare the old and new files.

If you're using Visual Studio, press F5 to build and run the code and interact with the console app. If you're using the .NET CLI, navigate to your application directory, then build and run the application.

dotnet build
dotnet run

The output of the app is similar to the following example:

Azure Blob Storage - .NET quickstart sample

Uploading to Blob storage as blob:
         https://mystorageacct.blob.core.windows.net/quickstartblobs60c70d78-8d93-43ae-954d-8322058cfd64/quickstart2fe6c5b4-7918-46cb-96f4-8c4c5cb2fd31.txt

Listing blobs...
        quickstart2fe6c5b4-7918-46cb-96f4-8c4c5cb2fd31.txt

Downloading blob to
        ./data/quickstart2fe6c5b4-7918-46cb-96f4-8c4c5cb2fd31DOWNLOADED.txt

Press any key to begin clean up
Deleting blob container...
Deleting the local source and downloaded files...
Done

Before you begin the clean up process, check your data folder for the two files. You can open them and observe that they are identical.

After you've verified the files, press the Enter key to delete the test files and finish the demo.

Next steps

In this quickstart, you learned how to upload, download, and list blobs using .NET.

To see Blob storage sample apps, continue to: