【问题标题】:How to get all files from a directory in Azure BLOB using ListBlobsSegmentedAsync如何使用 ListBlobsSegmentedAsync 从 Azure BLOB 中的目录中获取所有文件
【发布时间】:2019-01-22 03:54:18
【问题描述】:

在尝试访问 Azure blob 文件夹的所有文件时,获取了 container.ListBlobs(); 的示例代码,但它看起来很旧。

旧代码:container.ListBlobs();

新代码尝试:container.ListBlobsSegmentedAsync(continuationToken);

我正在尝试使用以下代码:

container.ListBlobsSegmentedAsync(continuationToken);

文件夹是这样的:

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

查找更新版本以从 Azure 文件夹中获取所有文件。 任何示例代码都会有所帮助,谢谢!

【问题讨论】:

  • 如果我的回答对您有帮助,您可以将其标记为答案,以帮助其他社区成员快速找到有用的信息,谢谢。

标签: c# azure containers blob azure-blob-storage


【解决方案1】:

这是答案的代码:

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;
}

然后您可以返回如下值:

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】:

    C#代码:

       //connection string
        string storageAccount_connectionString = "**NOTE: CONNECTION STRING**";
    
        // Retrieve storage account from connection string.
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageAccount_connectionString);
    
        // Create the blob client.
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    
        // Retrieve reference to a previously created container.
        CloudBlobContainer container = blobClient.GetContainerReference("**NOTE:NAME OF CONTAINER**");
        //The specified container does not exist
    
        try
        {
            //root directory
            CloudBlobDirectory dira = container.GetDirectoryReference(string.Empty);
            //true for all sub directories else false 
            var rootDirFolders = dira.ListBlobsSegmentedAsync(true, BlobListingDetails.Metadata, null, null, null, null).Result;
    
            foreach (var blob in rootDirFolders.Results)
            {
                 Console.WriteLine("Blob", blob);
            }
    
        }
        catch (Exception e)
        {
            //  Block of code to handle errors
            Console.WriteLine("Error", e);
    
        }
    

    【讨论】:

      【解决方案3】:

      CloudBlobClient.ListBlobsSegmentedAsync 方法用于返回包含容器中 blob 项集合的结果段。

      要列出所有的blob,我们可以使用ListBlobs方法,

      这是一个演示供您参考:

          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;
          }
      

      用法和截图:

      列出一个文件夹下的所有 blob 名称:

      列出一个文件夹下的所有 blob 的 URL:

      【讨论】:

      • 谢谢,但我使用 ListBlobsSegmentedAsync 和我的自定义逻辑解决了它,但是,据我尝试,ListBlobs 已不再使用.. :)
      • ListBlobs 已弃用并从 Azure SDK 中删除。
      【解决方案4】:

      更新: 使用 Azure.Storage.Blobs v12 - Package

      从目录中获取所有文件名
      var storageConnectionString = "DefaultEndpointsProtocol=...........=core.windows.net";
      var blobServiceClient = new BlobServiceClient(storageConnectionString);
      
      //get container
      var container = _blobServiceClient.GetBlobContainerClient("container_name");
              
      List<string> blobNames = new List<string>();
      
      //Enumerating the blobs may make multiple requests to the service while fetching all the values
      //Blobs are ordered lexicographically by name
      //if you want metadata set BlobTraits - BlobTraits.Metadata
      var blobHierarchyItems = container.GetBlobsByHierarchyAsync(BlobTraits.None, BlobStates.None, "/");
      
      await foreach (var blobHierarchyItem in blobHierarchyItems)
      {
         //check if the blob is a virtual directory.
         if (blobHierarchyItem.IsPrefix)
         {        
            // You can also access files under nested folders in this way,
            // of course you will need to create a function accordingly (you can do a recursive function)
            // var prefix = blobHierarchyItem.Name;
            // blobHierarchyItem.Name = "folderA\"
            // var blobHierarchyItems= container.GetBlobsByHierarchyAsync(BlobTraits.None, BlobStates.None, "/", prefix);     
          }
          else
          {
              blobNames.Add(blobHierarchyItem.Blob.Name);
          }    
      }
      

      还有更多的选项和示例你可以找到它here

      这是 nuget 包的 link

      【讨论】:

        猜你喜欢
        • 2021-03-12
        • 1970-01-01
        • 2020-12-01
        • 1970-01-01
        • 2022-07-05
        • 2019-08-14
        • 2014-09-15
        • 2017-08-20
        • 1970-01-01
        相关资源
        最近更新 更多