Search code examples
c#azureazure-storageazure-blob-storage

Get Azure blob container


I'm trying to get a container if it exists, if not, to create it.

My confusion is because GetBlobContainersAsync returns a BlobContainerItem and CreateBlobContainerAsync returns a BlobContainerClient.

When I find the container, how can I get the BlobContainerClient from the BlobContainerItem?

Here is what I have so far:

var blobServiceClient = new BlobServiceClient(this.ConnectionString);

BlobContainerItem archiveContainer = null;
await foreach (var container in blobServiceClient.GetBlobContainersAsync(prefix: Uploader.ContainerName))
{
    if (String.Compare(container.Name, Uploader.ContainerName,
        CultureInfo.CurrentCulture, CompareOptions.Ordinal) == 0)
    {
        archiveContainer = ???
        break;
    }
}

if (archiveContainer == null)
{
    archiveContainer = await blobServiceClient.CreateBlobContainerAsync(Uploader.ContainerName);
}

Solution

  • You don't really have to do all of this.

    Simply create an instance of BlobContainerClient using the connection string and container name and then call CreateIfNotExistsAsync on it. This method will create the container if it does not exist.

    From the documentation:

    The CreateIfNotExistsAsync(PublicAccessType, IDictionary<String,String>, BlobContainerEncryptionScopeOptions, CancellationToken) operation creates a new container under the specified account.
    If the container with the same name already exists, it is not changed.

    Something like:

    var blobContainerClient = new BlobContainerClient(this.ConnectionString, Uploader.ContainerName);
    await blobContainerClient.CreateIfNotExistsAsync();