Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 463
BG100 Avatar asked Feb 29 '16 16:02

BG100


People also ask

How do I delete Azure Files?

Sign into the Azure portal. Navigate to your storage account and select File shares under Data storage. Select Enabled next to Soft delete. Select Enabled for Soft delete for all file shares.


2 Answers

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
        }
    }
}
like image 86
Emily Gerner Avatar answered Oct 25 '22 22:10

Emily Gerner


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

public static async Task DeleteAllAsync(this ShareDirectoryClient dirClient) {

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

    await dirClient.DeleteAsync();
}

Call it like

var dirClient = shareClient.GetDirectoryClient("test");
await dirClient.DeleteAllAsync();
like image 35
Brad Patton Avatar answered Oct 25 '22 22:10

Brad Patton