How to delete files from blob container?

Remember SDK v11 has been deprecated, with SDK v12:

using Azure.Storage.Blobs;
...
BlobServiceClient blobServiceClient = new BlobServiceClient("StorageConnectionString");
BlobContainerClient cont = blobServiceClient.GetBlobContainerClient("containerName");
cont.GetBlobClient("FileName.ext").DeleteIfExists();

This is the code I use:

private CloudBlobContainer blobContainer;

public void DeleteFile(string uniqueFileIdentifier)
{
    this.AssertBlobContainer();

    var blob = this.blobContainer.GetBlockBlobReference(uniqueFileIdentifier);
    blob.DeleteIfExists();
}

private void AssertBlobContainer()
{
    // only do once
    if (this.blobContainer == null)
    {
        lock (this.blobContainerLockObj)
        {
            if (this.blobContainer == null)
            {
                var client = this.cloudStorageAccount.CreateCloudBlobClient();

                this.blobContainer = client.GetContainerReference(this.containerName.ToLowerInvariant());

                if (!this.blobContainer.Exists())
                {
                    throw new CustomRuntimeException("Container {0} does not exist in azure account", containerName);
                }
            }
        }
    }

    if (this.blobContainer == null) throw new NullReferenceException("Blob Empty");
}

You can ignore the locking code if you know this isn't going to be accessed simultaneously

Obviously, you have the blobContainer stuff sorted, so all you need is that DeleteFile method without the this.AssertBlobContainer().


There's a method called DeleteIfExistis(). Returns true/false.

CloudBlockBlob blob = CloudBlobContainer.GetBlockBlobReference(fileName);
blob.DeleteIfExists();

Filename is ContainerName/FileName, if is inside folders you need to mention the folder too. Like ContainerName/AppData/FileName and will work.

Tags:

C#

Azure