How do I delete all files in an Azure File Storage folder?

11,979

Solution 1

ListFilesAndDirectories can return both files and directories so you get a base class for those two. Then you can check which if the types it is and cast. Note you'll want to track any sub-directories so you can recursively delete the files in those.

var folder = root.GetDirectoryReference("myfolder");

if (folder.Exists())
{
    foreach (var item in folder.ListFilesAndDirectories())
    {         
        if (item.GetType() == typeof(CloudFile))
        {
            CloudFile file = (CloudFile)item;

            // Do whatever
        }

        else if (item.GetType() == typeof(CloudFileDirectory))
        {
            CloudFileDirectory dir = (CloudFileDirectory)item;

            // Do whatever
        }
    }
}

Solution 2

Took existing answers, fixed some bugs and created an extension method to delete the directory recursively

    public static async Task DeleteAllAsync(this ShareDirectoryClient dirClient) {
        var remaining = new Queue<ShareDirectoryClient>();
        remaining.Enqueue(dirClient);

        while (remaining.Count > 0) {
            ShareDirectoryClient dir = remaining.Dequeue();

            await foreach (ShareFileItem item in dir.GetFilesAndDirectoriesAsync()) {
                if (item.IsDirectory) {
                    var subDir = dir.GetSubdirectoryClient(item.Name);
                    await DeleteAllAsync(subDir);
                } else {
                    await dir.DeleteFileAsync(item.Name);
                }
            }

            await dir.DeleteAsync();
        }
    }

Call it like

    var dirClient = shareClient.GetDirectoryClient("test");
    await dirClient.DeleteAllAsync();

Solution 3

This recursive version works if you have 'directories' inside your 'directory'

       public void DeleteOutputDirectory()
       {
           var share = _fileClient.GetShareReference(_settings.FileShareName);
           var rootDir = share.GetRootDirectoryReference();

           DeleteDirectory(rootDir.GetDirectoryReference("DirName"));
       }

       private static void DeleteDirectory(CloudFileDirectory directory)
       {
           if (directory.Exists())
           {
               foreach (IListFileItem item in directory.ListFilesAndDirectories())
               {
                   switch (item)
                   {
                       case CloudFile file:
                           file.Delete();
                           break;
                       case CloudFileDirectory dir:
                           DeleteDirectory(dir);
                           break;
                   }
               }

               directory.Delete();
           }
       }

Solution 4

This implementation would be very easy to achieve with Recursion in PowerShell. Where you specify the directory [can be the root directory in your case] and then all contents of that directory including all files, subdirectories gets deleted. Refer to the github ready PowerShell for the same - https://github.com/kunalchandratre1/DeleteAzureFilesDirectoriesPowerShell

Share:
11,979
BG100
Author by

BG100

In my professional life, I'm a development manager for a Telecoms company in the UK. I manage a team of 4 developers and we build IVR based applications. Outside of that, I'm a member of a carnival club in Somerset (UK)... every year in November we have carnival processions of huge illuminated carnival floats running off a 800KVA generator with around 11,000 GLS light bulbs on it drawing around 2200amps.... and it's my job to wire the damn thing up!!

Updated on July 28, 2022

Comments

  • BG100
    BG100 almost 2 years

    I'm trying to work how how to delete all files in a folder in Azure File Storage.

    CloudFileDirectory.ListFilesAndDirectories() returns an IEnumerable of IListFileItem. But this doesn't help much because it doesn't have a filename property or similar.

    This is what I have so far:

    var folder = root.GetDirectoryReference("myfolder");
    
    if (folder.Exists()) {
        foreach (var file in folder.ListFilesAndDirectories()) {
    
            // How do I delete 'file'
    
        }
    }
    

    How can I change an IListFileItem to a CloudFile so I can call myfile.Delete()?

  • BG100
    BG100 about 8 years
    Perfect, thanks! I wondered if this might have been how to do it, but the MSDN docs around IListFileItem are really poor.
  • Carl
    Carl almost 5 years
    Thanks! I have to agree that the docs around all the C# Storage Account stuff are incredibly poor!
  • Miros
    Miros over 3 years
    That won't work - the first code sample is full of typos and bugs...
  • Miros
    Miros over 3 years
    And by the way (Microsoft are you looking?), this is how it's done using Dropbox API V2: using(var client = await GetClient()) { var res = await client.Files.DeleteV2Async(storagePath); }
  • Sugar Bowl
    Sugar Bowl about 2 years
    Why are you using Queue? Why can't one use the await foreach loop straightway?
  • Brad Patton
    Brad Patton about 2 years
    @SugarBowl - you are correct. The Queue was not needed. I had copied and modified one of the other answers to make this an extension method and did not notice that. I've updated the answer. Thanks for pointing it out.
  • Sugar Bowl
    Sugar Bowl about 2 years
    This is the way to go for Azure File Shares.