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

Sathish Nadarajan
 
Solution Architect
January 2, 2019
 
Rate this article
 
Views
15113

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)
             {
                 tempBlob.FetchAttributes();
 //If we want to delete the files based on any filter, we can do as below.
                 //if (tempBlob.Properties.Length > 16000000)
                 //{
                     System.Console.WriteLine(tempBlob.Name);
                     tempBlob.Delete(DeleteSnapshotsOption.IncludeSnapshots);
                 //}
             }
             
         }
 
 

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");
             lob.FetchAttributes();
             
 blob.Delete(DeleteSnapshotsOption.IncludeSnapshots);
 
 

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment