Get started with Azure Blob Storage and .NET

This article shows you how to connect to Azure Blob Storage by using the Azure Blob Storage client library v12 for .NET. Once connected, your code can operate on containers, blobs, and features of the Blob Storage service.

Package (NuGet) | Samples | API reference | Library source code | Give Feedback

Prerequisites

Set up your project

Open a command prompt and change directory (cd) into your project folder. Then, install the Azure Blob Storage client library for .NET package by using the dotnet add package command.

cd myProject
dotnet add package Azure.Storage.Blobs

Add these using statements to the top of your code file.

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

Connect to Blob Storage

To connect to Blob Storage, create an instance of the BlobServiceClient class. This object is your starting point. You can use it to operate on the blob service instance and it's containers. You can create a BlobServiceClient by using an account access key, a shared access signature (SAS), or by using an Azure Active Directory (Azure AD) authorization token.

To learn more about each of these authorization mechanisms, see Authorize access to data in Azure Storage.

Authorize with an account key

Create a StorageSharedKeyCredential by using the storage account name and account key. Then use that object to initialize a BlobServiceClient.

public static void GetBlobServiceClient(ref BlobServiceClient blobServiceClient,
    string accountName, string accountKey)
{
    Azure.Storage.StorageSharedKeyCredential sharedKeyCredential =
        new StorageSharedKeyCredential(accountName, accountKey);

    string blobUri = "https://" + accountName + ".blob.core.windows.net";

    blobServiceClient = new BlobServiceClient
        (new Uri(blobUri), sharedKeyCredential);
}

You can also create a BlobServiceClient by using a connection string.

    BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

For information about how to obtain account keys and best practice guidelines for properly managing and safeguarding your keys, see Manage storage account access keys.

Authorize with a SAS token

Create a Uri by using the blob service endpoint and SAS token. Then, create a BlobServiceClient by using the Uri.

public static void GetBlobServiceClientSAS(ref BlobServiceClient blobServiceClient,
    string accountName, string sasToken)
{
    string blobUri = "https://" + accountName + ".blob.core.windows.net";

    blobServiceClient = new BlobServiceClient
    (new Uri($"{blobUri}?{sasToken}"), null);
}

To generate and manage SAS tokens, see any of these articles:

Authorize with Azure AD

To authorize with Azure AD, you'll need to use a security principal. Which type of security principal you need depends on where your application runs. Use this table as a guide.

Where the application runs Security principal Guidance
Local machine (developing and testing) User identity or service principal Use the Azure Identity library to get an access token for authorization
Azure Managed identity Authorize access to blob data with managed identities for Azure resources
Servers or clients outside of Azure Service principal Authorize access to blob or queue data from a native or web application

If you're testing on a local machine, or your application will run in Azure virtual machines (VMs), function apps, virtual machine scale sets, or in other Azure services, obtain an OAuth token by creating a DefaultAzureCredential instance. Use that object to create a BlobServiceClient.

public static void GetBlobServiceClient(ref BlobServiceClient blobServiceClient, string accountName)
{
    TokenCredential credential = new DefaultAzureCredential();

    string blobUri = "https://" + accountName + ".blob.core.windows.net";

        blobServiceClient = new BlobServiceClient(new Uri(blobUri), credential);          
}

If you plan to deploy the application to servers and clients that run outside of Azure, you can obtain an OAuth token by using other classes in the Azure Identity client library for .NET which derive from the TokenCredential class.

This example creates a ClientSecretCredential instance by using the client ID, client secret, and tenant ID. You can obtain these values when you create an app registration and service principal.

public static void GetBlobServiceClientAzureAD(ref BlobServiceClient blobServiceClient,
    string accountName, string clientID, string clientSecret, string tenantID)
{

    TokenCredential credential = new ClientSecretCredential(
        tenantID, clientID, clientSecret, new TokenCredentialOptions());

    string blobUri = "https://" + accountName + ".blob.core.windows.net";

    blobServiceClient = new BlobServiceClient(new Uri(blobUri), credential);
}

Connect anonymously

If you explicitly enable anonymous access, then your code can create connect to Blob Storage without authorize your request. You can create a new service client object for anonymous access by providing the Blob storage endpoint for the account. However, you must also know the name of a container in that account that's available for anonymous access. To learn how to enable anonymous access, see Configure anonymous public read access for containers and blobs.

public static void CreateAnonymousBlobClient()
{
    // Create the client object using the Blob storage endpoint for your account.
    BlobServiceClient blobServiceClient = new BlobServiceClient
        (new Uri(@"https://storagesamples.blob.core.windows.net/"));

    // Get a reference to a container that's available for anonymous access.
    BlobContainerClient container = blobServiceClient.GetBlobContainerClient("sample-container");

    // Read the container's properties. 
    // Note this is only possible when the container supports full public read access.          
    Console.WriteLine(container.GetProperties().Value.LastModified);
    Console.WriteLine(container.GetProperties().Value.ETag);
}

Alternatively, if you have the URL to a container that is anonymously available, you can use it to reference the container directly.

public static void ListBlobsAnonymously()
{
    // Get a reference to a container that's available for anonymous access.
    BlobContainerClient container = new BlobContainerClient
        (new Uri(@"https://storagesamples.blob.core.windows.net/sample-container"));

    // List blobs in the container.
    // Note this is only possible when the container supports full public read access.
    foreach (BlobItem blobItem in container.GetBlobs())
    {
        Console.WriteLine(container.GetBlockBlobClient(blobItem.Name).Uri);
    }
}

Build your application

As you build your application, your code will primarily interact with three types of resources:

  • The storage account, which is the unique top-level namespace for your Azure Storage data.

  • Containers, which organize the blob data in your storage account.

  • Blobs, which store unstructured data like text and binary data.

The following diagram shows the relationship between these resources.

Diagram of Blob storage architecture

Each type of resource is represented by one or more associated .NET classes. These are the basic classes:

Class Description
BlobServiceClient Represents the Blob Storage endpoint for your storage account.
BlobContainerClient Allows you to manipulate Azure Storage containers and their blobs.
BlobClient Allows you to manipulate Azure Storage blobs.
AppendBlobClient Allows you to perform operations specific to append blobs such as periodically appending log data.
BlockBlobClient Allows you to perform operations specific to block blobs such as staging and then committing blocks of data.

The following guides show you how to use each of these classes to build your application.

Guide Description
Create a container Create containers.
Delete and restore containers Delete containers, and if soft-delete is enabled, restore deleted containers.
List containers List containers in an account and the various options available to customize a listing.
Manage properties and metadata Get and set properties and metadata for containers.
Create and manage leases Establish and manage a lock on a container or the blobs in a container.
Append data to blobs Learn how to create an append blob and then append data to that blob.
Upload blobs Learn how to upload blobs by using strings, streams, file paths, and other methods.
Download blobs Download blobs by using strings, streams, and file paths.
Copy blobs Copy a blob from one account to another account.
List blobs List blobs in different ways.
Delete and restore Delete blobs, and if soft-delete is enabled, restore deleted blobs.
Find blobs using tags Set and retrieve tags as well as use tags to find blobs.
Manage properties and metadata Get and set properties and metadata for blobs.

See also