Create and manage a blob snapshot with .NET

A snapshot is a read-only version of a blob that's taken at a point in time. This article shows how to create and manage blob snapshots using the Azure Storage client library for .NET.

For more information about blob snapshots in Azure Storage, see Blob snapshots.

Prerequisites

Set up your environment

If you don't have an existing project, this section shows you how to set up a project to work with the Azure Blob Storage client library for .NET. The steps include package installation, adding using directives, and creating an authorized client object. For details, see Get started with Azure Blob Storage and .NET.

Install packages

From your project directory, install packages for the Azure Blob Storage and Azure Identity client libraries using the dotnet add package command. The Azure.Identity package is needed for passwordless connections to Azure services.

dotnet add package Azure.Storage.Blobs
dotnet add package Azure.Identity

Add using directives

Add these using directives to the top of your code file:

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

Some code examples in this article might require additional using directives.

Create a client object

To connect an app to Blob Storage, create an instance of BlobServiceClient. The following example shows how to create a client object using DefaultAzureCredential for authorization:

public BlobServiceClient GetBlobServiceClient(string accountName)
{
    BlobServiceClient client = new(
        new Uri($"https://{accountName}.blob.core.windows.net"),
        new DefaultAzureCredential());

    return client;
}

You can also register a service client for dependency injection in a .NET app. To learn more about creating and managing client objects, see Create and manage client objects that interact with data resources.

Authorization

The authorization mechanism must have the necessary permissions to work with blob snapshots. For authorization with Microsoft Entra ID (recommended), you need Azure RBAC built-in role Storage Blob Data Contributor or higher. To learn more, see the authorization guidance for Snapshot Blob.

Create a snapshot

To create a snapshot of a block blob, use one of the following methods:

The following code example shows how to create a snapshot. Include a reference to the Azure.Identity library to use your Microsoft Entra credentials to authorize requests to the service. For more information about using the DefaultAzureCredential class to authorize a managed identity to access Azure Storage, see Azure Identity client library for .NET.

private static async Task CreateBlockBlobSnapshot(
    string accountName,
    string containerName, 
    string blobName,
    Stream data)
{
    const string blobServiceEndpointSuffix = ".blob.core.windows.net";
    Uri containerUri = 
        new Uri("https://" + accountName + blobServiceEndpointSuffix + "/" + containerName);

    // Get a container client object and create the container.
    BlobContainerClient containerClient = new BlobContainerClient(containerUri,
        new DefaultAzureCredential());
    await containerClient.CreateIfNotExistsAsync();

    // Get a blob client object.
    BlobClient blobClient = containerClient.GetBlobClient(blobName);

    try
    {
        // Upload text to create a block blob.
        await blobClient.UploadAsync(data);

        // Add blob metadata.
        IDictionary<string, string> metadata = new Dictionary<string, string>
        {
            { "ApproxBlobCreatedDate", DateTime.UtcNow.ToString() },
            { "FileType", "text" }
        };
        await blobClient.SetMetadataAsync(metadata);

        // Sleep 5 seconds.
        System.Threading.Thread.Sleep(5000);

        // Create a snapshot of the base blob.
        // You can specify metadata at the time that the snapshot is created.
        // If no metadata is specified, then the blob's metadata is copied to the snapshot.
        await blobClient.CreateSnapshotAsync();
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine(e.Message);
        Console.ReadLine();
        throw;
    }
}

Delete snapshots

To delete a blob, you must first delete any snapshots of that blob. You can delete a snapshot individually, or specify that all snapshots be deleted when the source blob is deleted. If you attempt to delete a blob that still has snapshots, an error results.

To delete a blob and its snapshots, use one of the following methods, and include the DeleteSnapshotsOption enum:

The following code example shows how to delete a blob and its snapshots in .NET, where blobClient is an object of type BlobClient:

await blobClient.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots, null, default);

Copy a blob snapshot over the base blob

You can perform a copy operation to promote a snapshot over its base blob, as long as the base blob is in an online tier (hot or cool). The snapshot remains, but its destination is overwritten with a copy that can be read and written to.

The following code example shows how to copy a blob snapshot over the base blob:

public static async Task<BlockBlobClient> CopySnapshotOverBaseBlobAsync(
    BlockBlobClient client,
    string snapshotTimestamp)
{
    // Instantiate BlockBlobClient with identical URI and add snapshot timestamp
    BlockBlobClient snapshotClient = client.WithSnapshot(snapshotTimestamp);

    // Restore the specified snapshot by copying it over the base blob
    await client.SyncUploadFromUriAsync(snapshotClient.Uri, overwrite: true);

    // Return the client object after the copy operation
    return client;
}

Resources

To learn more about managing blob snapshots using the Azure Blob Storage client library for .NET, see the following resources.

For related code samples using deprecated .NET version 11.x SDKs, see Code samples using .NET version 11.x.

Client library resources

See also