Dave
Dave

Reputation: 2601

Azure Blob Storage throws exception when creating a new container. Claims it already exists, but it does not

I am trying to create a blob container in Azure storage using the sample code below.

        BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
        var fileName = "quickstart" + Guid.NewGuid().ToString() + ".png";

        //Create a unique name for the container
        string containerName = "quickstartblobs" + Guid.NewGuid().ToString();

        BlobContainerClient containerClient = blobServiceClient.CreateBlobContainer(containerName); //Exception occurs here. 
        BlobClient blobClient = containerClient.GetBlobClient(fileName);

        var result = blobClient.Upload(ms);

Despite making a new container name that clearly doesn't exist, the call to CreateBlobContainer() always creates the container in Azure and then throws an exception saying it already exists.

'The specified container already exists.

I verify in my Azure environment that no containers exist prior to running this code. While searching for a resolution to this problem, I have seen references to a CreateIfNotExists() method, however I don't see that method available on BlobServiceClient.

Can someone explain why this is not working as expected and what to do about it?

Upvotes: 1

Views: 4818

Answers (2)

Harsha
Harsha

Reputation: 1

use overload method bloabClient.Upload(string path,bool overwite)

bloabClient.Upload(ms,true);

this may help, thanks

Ex:

BlobContainerClient container = await blobServiceClient.CreateBlobContainerAsync("employeeblob");
        BlobClient blobClient = container.GetBlobClient("emp.xlsx");
        await blobClient.UploadAsync(fileName,true);

ex: screeshot

Upvotes: 0

Frank Borzage
Frank Borzage

Reputation: 6796

You can use the following code to solve your problem:

        BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
        var fileName = "quickstart" + Guid.NewGuid().ToString() + ".png";

        //Create a unique name for the container
        string containerName = "quickstartblobs" + Guid.NewGuid().ToString();

        BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
        containerClient.CreateIfNotExists(); 
        BlobClient blobClient = containerClient.GetBlobClient(fileName);

        var result = blobClient.Upload(ms);

Upvotes: 1

Related Questions