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