26
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?

  • 2
    Possible duplicate of [How to clean an Azure storage Blob container?](http://stackoverflow.com/questions/10426213/how-to-clean-an-azure-storage-blob-container) – Bushuev Apr 08 '16 at 11:08
  • 3
    @h.o.m.a.n He want's to be able to delete specific blobs, not the whole thing though.. – Callum Linington Apr 08 '16 at 12:55
  • @CallumLinington you can modify this code to remove some files from container like this 'Parallel.ForEach(_cloudBlobClient.GetContainerReference(nameContainer).ListBlobs(), x => { if (list.Contains(((CloudBlob)x).Name)) ((CloudBlob)x).DeleteIfExists(); });' – Bushuev Apr 08 '16 at 13:15

6 Answers6

42

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

Ellis Thompson
  • 408
  • 6
  • 18
Callum Linington
  • 14,213
  • 12
  • 75
  • 154
17

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();
mainmind83
  • 491
  • 4
  • 7
  • I get the error: The specified resource name length is not within the permissible limits – Jnr Jul 28 '21 at 17:42
  • @JNr this is another error: https://stackoverflow.com/questions/57328134/the-specified-resource-name-length-is-not-within-the-permissible-limits-azure-bl – mainmind83 Sep 22 '21 at 10:41
3

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.

Guilherme Flores
  • 369
  • 3
  • 15
2

A single line code to perform deletion

private static async Task DeleteBLOBFile(string blobNamewithFileExtension)
        {
            BlobClient blobClient = new BlobClient(blobConnectionString,containerName,blobNamewithFileExtension);
            await blobClient.DeleteIfExistsAsync();            
        }
1

We can use the cloudBlobContainer.ListBlobsSegmentedAsync to list the blobs and then cast it as ICloudBlob so that you can perform the DeleteIfExistsAsync. Below is the working sample function. Hope it helps.

public async Task < bool > PerformTasks() {
    try {
        if (CloudStorageAccount.TryParse(StorageConnectionString, out CloudStorageAccount cloudStorageAccount)) {
            var cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
            var cloudBlobContainer = cloudBlobClient.GetContainerReference(_blobContainerName);
            if (await cloudBlobContainer.ExistsAsync()) {
                BlobContinuationToken blobContinuationToken = null;
                var blobList = await cloudBlobContainer.ListBlobsSegmentedAsync(blobContinuationToken);
                var cloudBlobList = blobList.Results.Select(blb = >blb as ICloudBlob);
                foreach(var item in cloudBlobList) {
                    await item.DeleteIfExistsAsync();
                }
                return true;
            }
            else {
                _logger.LogError(ErrorMessages.NoBlobContainerAvailable);
            }
        }
        else {
            _logger.LogError(ErrorMessages.NoStorageConnectionStringAvailable);
        }
    }
    catch(Exception ex) {
        _logger.LogError(ex.Message);
    }
    return false;
}
Sibeesh Venu
  • 18,755
  • 12
  • 103
  • 140
-1
List<string> FileNameList = new List<string>();
FileNameList = fileName.Split(',').Where(t => t.ToString().Trim() != "").ToList();
CloudBlobClient client;
CloudBlobContainer container;
CloudBlockBlob blob;
string accessKey;
string accountName;
string connectionString;
accessKey = Environment.GetEnvironmentVariable("StorageAccountaccessKey");
accountName = Environment.GetEnvironmentVariable("StorageAccountName");
connectionString = Environment.GetEnvironmentVariable("StorageAccountConnectionString");
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
client = storageAccount.CreateCloudBlobClient();
string containerName = tenantId;
container = client.GetContainerReference(containerName);

foreach(var file in FileNameList)
{
   blob = container.GetBlockBlobReference(file);
   blob.DeleteIfExists();
}
Ami
  • 7
  • 1
  • This code works but it's a mess. Unused variables, bad naming, etc. Please clean it up if you are going to submit it for others. – smurtagh Feb 17 '20 at 21:49