Επεξεργασία

Κοινή χρήση μέσω


Delete and restore a blob container with .NET

This article shows how to delete containers with the Azure Storage client library for .NET. If you've enabled container soft delete, you can restore deleted containers.

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 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 or restore a container. 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 Container (REST API) and Restore Container (REST API).

Delete a container

To delete a container in .NET, use one of the following methods:

The Delete and DeleteAsync methods throw an exception if the container doesn't exist.

The DeleteIfExists and DeleteIfExistsAsync methods return a Boolean value indicating whether the container was deleted. If the specified container doesn't exist, then these methods return False to indicate that the container wasn't deleted.

After you delete a container, you can't create a container with the same name for at least 30 seconds. Attempting to create a container with the same name will fail with HTTP error code 409 (Conflict). Any other operations on the container or the blobs it contains will fail with HTTP error code 404 (Not Found).

The following example deletes the specified container, and handles the exception if the container doesn't exist:

//-------------------------------------------------
// Delete a container
//-------------------------------------------------
private static async Task DeleteSampleContainerAsync(BlobServiceClient blobServiceClient, string containerName)
{
    BlobContainerClient container = blobServiceClient.GetBlobContainerClient(containerName);

    try
    {
        // Delete the specified container and handle the exception.
        await container.DeleteAsync();
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine("HTTP error code {0}: {1}",
                            e.Status, e.ErrorCode);
        Console.WriteLine(e.Message);
        Console.ReadLine();
    }
}

The following example shows how to delete all of the containers that start with a specified prefix.

//-------------------------------------------------
// Delete all containers with the specified prefix
//-------------------------------------------------
private static async Task DeleteContainersWithPrefixAsync(BlobServiceClient blobServiceClient, string prefix)
{
    Console.WriteLine("Delete all containers beginning with the specified prefix");

    try
    {
        foreach (BlobContainerItem container in blobServiceClient.GetBlobContainers())
        {
            if (container.Name.StartsWith(prefix))
            { 
                Console.WriteLine("\tContainer:" + container.Name);
                BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(container.Name);
                await containerClient.DeleteAsync();
            }
        }

        Console.WriteLine();
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine(e.Message);
        Console.ReadLine();
        throw;
    }
}

Restore a deleted container

When container soft delete is enabled for a storage account, a container and its contents may be recovered after it has been deleted, within a retention period that you specify. You can restore a soft-deleted container by calling either of the following methods of the BlobServiceClient class.

The following example finds a deleted container, gets the version ID of that deleted container, and then passes that ID into the UndeleteBlobContainerAsync method to restore the container.

public static async Task RestoreContainer(BlobServiceClient client, string containerName)
{
    await foreach (BlobContainerItem item in client.GetBlobContainersAsync
        (BlobContainerTraits.None, BlobContainerStates.Deleted))
    {
        if (item.Name == containerName && (item.IsDeleted == true))
        {
            try 
            { 
                await client.UndeleteBlobContainerAsync(containerName, item.VersionId);
            }
            catch (RequestFailedException e)
            {
                Console.WriteLine("HTTP error code {0}: {1}",
                e.Status, e.ErrorCode);
                Console.WriteLine(e.Message);
            }
        }
    }
}

Resources

To learn more about deleting a container using the Azure Blob Storage client library for .NET, see the following resources.

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 or restoring a container 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.