How to get all files from a directory in Azure BLO

2019-08-29 10:11发布

问题:

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!

回答1:

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;


回答2:

The method CloudBlobClient.ListBlobsSegmentedAsync is used to return a result segment containing a collection of blob items in the container.

To list all blobs, we can use ListBlobs method,

Here is a demo for your reference:

    public static List<V> ListAllBlobs<T, V>(Expression<Func<T, V>> expression, string containerName,string prefix)
    {
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse("YourConnectionString;");

        CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();

        CloudBlobContainer container = cloudBlobClient.GetContainerReference(containerName);
        container.CreateIfNotExists();

        var list = container.ListBlobs(prefix: prefix,useFlatBlobListing: true);

        List<V> data = list.OfType<T>().Select(expression.Compile()).ToList();
        return data;
    }

Usage and screenshots:

List all blobs' names under one folder:

List all blobs' URLs under one folder: