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()
?
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.
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
}
}
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With