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

4

29

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.

Deontology answered 9/4, 2020 at 19:28 Comment(0)
D
52

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();
Deuteranope answered 10/4, 2020 at 1:1 Comment(8)
Thanks for all the code examples Ivan, that's ready helpful and works well for my requirements.Deontology
I have tried this but calling Exists() throws an exception saying the container does not exists, WTF Microsoft.Monahon
@Phil, what's the package and version are you using? you'd better provide some sample code:)Deuteranope
I'm partly to blame, I'm using the Uri overload for new BlobContainerClient(new Uri("..")); I wasn't passing in an TokenCredential e.g. , new DefaultAzureCredential(). The error could of been more helpful and hinted at an authorisation problem instead of a 404.Monahon
@IvanYang Do you know if there is any limitation when using a SAS instead of the connection string? When using the connection string it works perfectly, but when I use a SAS token it throws an exception saying that the blob does not exist, but the check is for a container, so I do not understand the error.Tie
@Tie there are lots of configurations when generate sas_token, so if you're missing some configurations, there maybe an error occurs. You'd better let us know the details of how do you generate your sas_token, and how to use it.Deuteranope
@IvanYang I have posted the question and the code. Thanks!Tie
I seem to be missing something: bool isExist = container.Exists(); doesn't compile for me, as Exists() does not return a bool, but a Response<bool> now.Damages
D
8

The accepted answer is fine. But I usually use the async version of it.

var _blobServiceClient = new BlobServiceClient(YOURCONNECTIONSTRING);
var containerClient = _blobServiceClient.GetBlobContainerClient(YOURCONTAINERNAME);
await containerClient.CreateIfNotExistsAsync(Azure.Storage.Blobs.Models.PublicAccessType.BlobContainer);

The version I'm using is Azure.Storage.Blobs v12.4.1

Dolor answered 18/4, 2020 at 19:27 Comment(0)
A
2

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.

I am not sure why do you say CreateIfNotExists is no longer available in version 12 of storage client library. It is certainly there in BlobContainerClient class. Here's the direct link: CreateIfNotExists.

    var connectionString = "UseDevelopmentStorage=true";            
    var containerClient = new BlobContainerClient(connectionString, containerName);
    containerClient.CreateIfNotExists();
Actual answered 10/4, 2020 at 7:50 Comment(1)
Thanks for the link Gaurav, that's helpful. I simply couldn't find any code examples for V12 using CreateIfNotExists and had read somewhere it was no longer available.Deontology
T
-1

I have the following method to get a SAS token, everything works fine.

private Uri GetUriSasToken()
    {
        string storedPolicyName = null;
        string connectionString = _config.GetConnectionString("BlobConnection");
        BlobContainerClient containerClient = new BlobContainerClient(connectionString, "stock");

        // Check whether this BlobContainerClient object has been authorized with Shared Key.
        if (containerClient.CanGenerateSasUri)
        {
            // Create a SAS token that's valid for one hour.
            BlobSasBuilder sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = containerClient.Name,
                Resource = "c"
            };

            if (storedPolicyName == null)
            {
                sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
                sasBuilder.SetPermissions(BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List);
            }
            else
            {
                sasBuilder.Identifier = storedPolicyName;
            }

            Uri sasUri = containerClient.GenerateSasUri(sasBuilder);
            return sasUri;
        }
        else
        {
            _logger.LogError(@"BlobContainerClient must be authorized with Shared Key credentials to create a service SAS.");
            return null;
        }
                 
    }

Then, I call the above method with the following code:

   BlobServiceClient blobServiceClient = new BlobServiceClient(GetUriSasToken(), null);
        var blobName = _config.GetValue<string>("BlobName");
        var containerName = _config.GetValue<string>("ContainerName");            
        var fileName = _config.GetValue<string>("FileName");            
        var containerClient = blobServiceClient.GetBlobContainerClient(containerName);

Is there any way I can verify that the container exists?

I'm not sure I can do:

containerClient.Exists

I used it but it returns an error that the Blob does not exists, but I want to check first if the container exists.

Anyone has done this?

Tie answered 22/1, 2021 at 4:27 Comment(3)
I see in the GetUriSasToken() method, you specify a container name "stock" when generating sas_token. then this sas_token can only be used for that container "stock". You'd better creating an account level sas_token:).Deuteranope
@IvanYang got you. Thank you for the clarification. Do you know how to create this account level token? I saw this page in the doc learn.microsoft.com/en-us/rest/api/storageservices/… but it is not clear to me how to specify the account level scope?Tie
can you please add a new question in stackoverflow, and then let me know the link to the question? just notice that what you added is an answer, not a question.Deuteranope

© 2022 - 2024 — McMap. All rights reserved.