Create or delete a container in Azure Storage with .NET

Blobs in Azure Storage are organized into containers. Before you can upload a blob, you must first create a container. This article shows how to create and delete containers with the Azure Storage client library for .NET.

Name a container

A container name must be a valid DNS name, as it forms part of the unique URI used to address the container or its blobs. Follow these rules when naming a container:

  • Container names can be between 3 and 63 characters long.
  • Container names must start with a letter or number, and can contain only lowercase letters, numbers, and the dash (-) character.
  • Two or more consecutive dash characters aren't permitted in container names.

The URI for a container is in this format:

https://myaccount.blob.core.windows.net/mycontainer

Create a container

To create a container, call one of the following methods:

These methods throw an exception if a container with the same name already exists.

Containers are created immediately beneath the storage account. It's not possible to nest one container beneath another.

The following example creates a container asynchronously:

//-------------------------------------------------
// Create a container
//-------------------------------------------------
private static async Task<BlobContainerClient> CreateSampleContainerAsync(BlobServiceClient blobServiceClient)
{
    // Name the sample container based on new GUID to ensure uniqueness.
    // The container name must be lowercase.
    string containerName = "container-" + Guid.NewGuid();

    try
    {
        // Create the container
        BlobContainerClient container = await blobServiceClient.CreateBlobContainerAsync(containerName);

        if (await container.ExistsAsync())
        {
            Console.WriteLine("Created container {0}", container.Name);
            return container;
        }
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine("HTTP error code {0}: {1}",
                            e.Status, e.ErrorCode);
        Console.WriteLine(e.Message);
    }

    return null;
}

Create the root container

A root container serves as a default container for your storage account. Each storage account may have one root container, which must be named $root. The root container must be explicitly created or deleted.

You can reference a blob stored in the root container without including the root container name. The root container enables you to reference a blob at the top level of the storage account hierarchy. For example, you can reference a blob that is in the root container in the following manner:

https://myaccount.blob.core.windows.net/default.html

The following example creates the root container synchronously:

//-------------------------------------------------
// Create root container
//-------------------------------------------------
private static void CreateRootContainer(BlobServiceClient blobServiceClient)
{
    try
    {
        // Create the root container or handle the exception if it already exists
        BlobContainerClient container =  blobServiceClient.CreateBlobContainer("$root");

        if (container.Exists())
        {
            Console.WriteLine("Created root container.");
        }
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine("HTTP error code {0}: {1}",
                            e.Status, e.ErrorCode);
        Console.WriteLine(e.Message);
    }
}

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;
    }
}

Resources for development with .NET

The links below provide useful resources for developers using the Azure Storage client library for .NET.

Azure Storage common APIs

Blob storage APIs

.NET tools

See also