Delete and restore a blob with .NET

This article shows how to delete blobs with the Azure Storage client library for .NET, and how to restore soft-deleted blobs during the retention period.

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.chinacloudapi.cn"),
        new DefaultAzureCredential());

    return client;
}

You can register a service client for dependency injection in a .NET app.

You can also create client objects for specific containers or blobs. 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 delete a blob, or to restore a soft-deleted blob. 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 Delete Blob (REST API) and Undelete Blob (REST API).

Delete a blob

Note

When blob soft delete is enabled for a storage account, you can't perform a permanent deletion using client library methods. Using the methods in this article, a soft-deleted blob, blob version, or snapshot remains available until the retention period expires, at which time it's permanently deleted. To learn more about the underlying REST API operation, see Delete Blob (REST API).

To delete a blob, call any of the following methods:

The following example deletes a blob:

public static async Task DeleteBlobAsync(BlobClient blob)
{
    await blob.DeleteAsync();
}

If the blob has any associated snapshots, you must delete all of its snapshots to delete the blob. The following example deletes a blob and its snapshots:

public static async Task DeleteBlobSnapshotsAsync(BlobClient blob)
{
    // Delete a blob and all of its snapshots
    await blob.DeleteAsync(snapshotsOption: DeleteSnapshotsOption.IncludeSnapshots);

    // Delete only the blob's snapshots
    //await blob.DeleteAsync(snapshotsOption: DeleteSnapshotsOption.OnlySnapshots);
}

To delete only the snapshots and not the blob itself, you can pass the parameter DeleteSnapshotsOption.OnlySnapshots.

Restore a deleted blob

Blob soft delete protects an individual blob and its versions, snapshots, and metadata from accidental deletes or overwrites by maintaining the deleted data in the system for a specified period of time. During the retention period, you can restore the blob to its state at deletion. After the retention period has expired, the blob is permanently deleted. For more information about blob soft delete, see Soft delete for blobs.

You can use the Azure Storage client libraries to restore a soft-deleted blob or snapshot.

How you restore a soft-deleted blob depends on whether or not your storage account has blob versioning enabled. For more information on blob versioning, see Blob versioning. See one of the following sections, depending on your scenario:

Restore soft-deleted objects when versioning is disabled

To restore deleted blobs when versioning is not enabled, call either of the following methods:

These methods restore soft-deleted blobs and any deleted snapshots associated with them. Calling either of these methods for a blob that has not been deleted has no effect. The following example restores all soft-deleted blobs and their snapshots in a container:

public static async Task RestoreBlobsAsync(BlobContainerClient container)
{
    foreach (BlobItem blob in container.GetBlobs(BlobTraits.None, BlobStates.Deleted))
    {
        await container.GetBlockBlobClient(blob.Name).UndeleteAsync();
    }
}

To restore a specific soft-deleted snapshot, first call the Undelete or UndeleteAsync on the base blob, then copy the desired snapshot over the base blob. The following example restores a block blob to the most recently generated snapshot:

public static async Task RestoreSnapshotsAsync(
    BlobContainerClient container,
    BlobClient blob)
{
    // Restore the deleted blob
    await blob.UndeleteAsync();

    // List blobs in this container that match prefix
    // Include snapshots in listing
    Pageable<BlobItem> blobItems = container.GetBlobs(
        BlobTraits.None,
        BlobStates.Snapshots,
        prefix: blob.Name);

    // Get the URI for the most recent snapshot
    BlobUriBuilder blobSnapshotUri = new BlobUriBuilder(blob.Uri)
    {
        Snapshot = blobItems
            .OrderByDescending(snapshot => snapshot.Snapshot)
            .ElementAtOrDefault(0)?.Snapshot
    };

    // Restore the most recent snapshot by copying it to the blob
    await blob.StartCopyFromUriAsync(blobSnapshotUri.ToUri());
}

Restore soft-deleted blobs when versioning is enabled

If a storage account is configured to enable blob versioning, deleting a blob causes the current version of the blob to become the previous version. To restore a soft-deleted blob when versioning is enabled, copy a previous version over the base blob. You can use either of the following methods:

The following code example shows how to get the latest version of a deleted blob, and restore the latest version by copying it to the base blob:

public static void RestoreBlobWithVersioning(
    BlobContainerClient container,
    BlobClient blob)
{
    // List blobs in this container that match prefix
    // Include versions in listing
    Pageable<BlobItem> blobItems = container.GetBlobs(
        BlobTraits.None,
        BlobStates.Version,
        prefix: blob.Name);

    // Get the URI for the most recent version
    BlobUriBuilder blobVersionUri = new BlobUriBuilder(blob.Uri)
    {
        VersionId = blobItems.
            OrderByDescending(version => version.VersionId).
            ElementAtOrDefault(0)?.VersionId
    };

    // Restore the most recently generated version by copying it to the base blob
    blob.StartCopyFromUri(blobVersionUri.ToUri());
}

Resources

To learn more about how to delete blobs and restore deleted blobs using the Azure Blob Storage client library for .NET, see the following resources.

Code samples

REST API operations

The Azure SDK for .NET contains libraries that build on top of the Azure REST API, allowing you to interact with REST API operations through familiar .NET paradigms. The client library methods for deleting blobs and restoring deleted blobs use the following REST API operations:

Client library resources

See also

  • This article is part of the Blob Storage developer guide for .NET. To learn more, see the full list of developer guide articles at Build your .NET app.