How to get all files from a directory in Azure BLOB using ListBlobsSegmentedAsync

Gaurav Kaushik picture Gaurav Kaushik · Aug 15, 2018 · Viewed 11.6k times · Source

While trying to access all files of the Azure blob folder, getting sample code for container.ListBlobs(); however it looks like an old one.

Old Code : container.ListBlobs();

New Code trying : container.ListBlobsSegmentedAsync(continuationToken);

I am trying to use the below code :

container.ListBlobsSegmentedAsync(continuationToken);

Folders are like :

Container/F1/file.json
Container/F1/F2/file.json
Container/F2/file.json

Looking for the updated version to get all files from an Azure folder. Any sample code would help, thanks!

Answer

Gaurav Kaushik picture Gaurav Kaushik · Aug 17, 2018

Here is the code for the Answer :

private async Task<List<IListBlobItem>> ListBlobsAsync(CloudBlobContainer container)
{
    BlobContinuationToken continuationToken = null;
    List<IListBlobItem> results = new List<IListBlobItem>();
    do
    {
       bool useFlatBlobListing = true;
       BlobListingDetails blobListingDetails = BlobListingDetails.None;
       int maxBlobsPerRequest = 500;
       var response = await container.ListBlobsSegmentedAsync(BOAppSettings.ConfigServiceEnvironment, useFlatBlobListing, blobListingDetails, maxBlobsPerRequest, continuationToken, null, null);
            continuationToken = response.ContinuationToken;
            results.AddRange(response.Results);
        }
     while (continuationToken != null);
     return results;
}

And then you can return values like:

IEnumerable<IListBlobItem> listBlobs = await this.ListBlobsAsync(container);
foreach(CloudBlockBlob cloudBlockBlob in listBlobs)
  {
     BOBlobFilesViewModel boBlobFilesViewModel = new BOBlobFilesViewModel
     {
          CacheKey = cloudBlockBlob.Name,
          Name = cloudBlockBlob.Name
      };
      listBOBlobFilesViewModel.Add(boBlobFilesViewModel);
   }
//return listBOBlobFilesViewModel;