Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete files from blob container?

Tags:

c#

azure

private readonly CloudBlobContainer _blobContainer;

public void Remove()
{
    if (_blobContainer.Exists())
    {
       _blobContainer.Delete();
    }
}

How to delete not a whole container but some List<string> disks that in the container?


1 Answers

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().

like image 144
Callum Linington Avatar answered Sep 09 '25 03:09

Callum Linington