Search code examples
azureasp.net-coreazure-storageazure-blob-storage

How do you check that a container exists in Azure Blob Storage V12


Previously when using Azure Blob Storage SDK V11, if you wanted to Create a container but were unsure if the container existed you could use CreateIfNotExists.

However in version V12, CreateIfNotExists is no longer available and the only example I can find from Microsoft is to simply create a Container without checking if it already exists.

So, does anyone know the best practice in V12 to check if a container exists before trying to create it.

Incidentally, I'm developing for ASP.Net Core 3.1.


Solution

  • In v12, there are 2 ways to check if the container exists or not.

    1.

    BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
    
    //get a BlobContainerClient
    var container = blobServiceClient.GetBlobContainerClient("the container name");
                
    //you can check if the container exists or not, then determine to create it or not
    bool isExist = container.Exists();
    if (!isExist)
    {
        container.Create();
    }
    
    //or you can directly use this method to create a container if it does not exist.
     container.CreateIfNotExists();
    

    You can directly create a BlobContainerClient, then use code below:

    //create a BlobContainerClient 
    BlobContainerClient blobContainer = new BlobContainerClient("storage connection string", "the container name");
        
    //use code below to check if the container exists, then determine to create it or not
    bool isExists = blobContainer.Exists();
    if (!isExist)
    {
       blobContainer .Create();
    }
        
    //or use this code to create the container directly, if it does not exist.
    blobContainer.CreateIfNotExists();