How to Delete the Blobs from the Azure Blob Container Using C# Programmatically

Sathish Nadarajan
SharePoint MVP
Published On :   02 Jan 2019
Visit Count
Today :  2    Total :   193

In the earlier article, we saw how to retrieve the Blobs from an Azure Container Using C#. In this article, as a continuation, let us see, how to delete them. This scenario is for clean up the Blobs during the development time. I faced this, when I needed to delete thousands of files from the Blob Container. It is not possible to delete one by one or on the page in the Azure Console, there is no select all option. Hence, did the clean-up programmatically.

The code is straight forward and a continuation of the earlier article itself.

 public static void DeleteFilesFromBlob()
 //Set the connection string variable
             string storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=*****";
             // Retrieve storage account from connection string.
             CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
             // Create the blob client.
             CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
             // Retrieve reference to a previously created container.
             CloudBlobContainer container = blobClient.GetContainerReference("bwsacontainer");
 // Get the directory from which we need to delete the files
             CloudBlobDirectory dira = container.GetDirectoryReference("development21nov");
             //Gets List of Blobs
             var list = dira.ListBlobs();
             var blobNames = list.OfType<CloudBlockBlob>().ToList();
             foreach (var tempBlob in blobNames)
 //If we want to delete the files based on any filter, we can do as below.
                 //if (tempBlob.Properties.Length > 16000000)

If we want to delete a specific file,

 // The below code is to delete a specific file
             var blob = dira.GetBlobReference("Stat_2018_11_21_10_35_03_p.m._can_(452).PDF");

Happy Coding,

Sathish Nadarajan.