Let's start with an example of how to delete a “folder” using ListBlobsSegmentedAsyc:
var container = // get container reference var ctoken = new BlobContinuationToken(); do { var result = await container.ListBlobsSegmentedAsync("myfolder", true, BlobListingDetails.None, null, ctoken, null, null); ctoken = result.ContinuationToken; await Task.WhenAll(result.Results .Select(item => (item as CloudBlob)?.DeleteIfExistsAsync()) .Where(task => task != null) ); } while (ctoken != null);
What does it do ...
var ctoken = new BlobContinuationToken();
A folder can contain many files. ListBlobSegmentedAsyc can return only a part of them. This token will store information where to continue in the next call.
var result = await container.ListBlobsSegmentedAsync("myfolder", true, BlobListingDetails.None, null, ctoken, null, null);
- The first argument is the required prefix for the blob name ("path").
- The second argument, "useFlatBlobListing = true", instructs the client to return all items in all subfolders. If set to false, it will work in the "virtual folders" mode and behave like a file system.
- Ctoken will tell azure where to continue
For all arguments, see https://docs.microsoft.com/en-us/dotnet/api/microsoft.windowsazure.storage.blob.cloudblobclient.listblobssegmentedasync?view=azure-dotnet for details.
(item as CloudBlob)?.DeleteIfExistsAsync()
Now we have a list of IListBlobItem as a result. Results. Since IListBlobItem is not guaranteed to be a removable CloudBlob (for example, it could be a virtual folder if we set useFlatBlobListing = false), we are trying to bring it to action and delete it if possible.
result.Results.Select(item => (item as CloudBlob)?.DeleteIfExistsAsync())
Triggers delete for all results and returns a list of tasks.
.Where(task => task != null)
If the Results contained elements that we could not convert to CloudBlob, our task list would contain null values. We must remove them.
... then we wait until all deletions for the current segment are completed, and continue with the next segment, if available.