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

BG100 picture BG100 · Feb 29, 2016 · Viewed 8.7k times · Source

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

Answer

Emily Gerner picture Emily Gerner · Feb 29, 2016

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
        }
    }
}