【问题标题】:How to get a list of all folders in an container in Blob Storage?如何获取 Blob 存储中容器中所有文件夹的列表?
【发布时间】:2017-10-27 13:24:48
【问题描述】:

我正在使用 Azure Blob 存储来存储我的一些文件。我将它们分类在不同的文件夹中。

到目前为止,我可以使用以下方法获取容器中所有 blob 的列表:

    public async Task<List<Uri>> GetFullBlobsAsync()
    {
        var blobList = await Container.ListBlobsSegmentedAsync(string.Empty, true, BlobListingDetails.None, int.MaxValue, null, null, null);

        return (from blob in blobList.Results where !blob.Uri.Segments.LastOrDefault().EndsWith("-thumb") select blob.Uri).ToList();
    }

但我怎样才能只获取文件夹,然后可能是该特定子目录中的文件?

顺便说一句,这是在 ASP.NET Core 上

编辑:

容器结构如下:

Container  
|  
|  
____Folder 1  
|   ____File 1  
|   ____File 2  
|   
|  
____Folder 2   
    ____File 3  
    ____File 4  
    ____File 5  
    ____File 6  

【问题讨论】:

  • 不确定你想要的。例如,您想要容器中的所有文件夹,无论级别如何,还是您只想要顶级文件和文件夹?
  • 我更新了一些文件夹结构。我很想得到类似GetFolders(container) 的东西。然后也许像GetFilesInFolder(path/to/folder)

标签: c# azure asp.net-core azure-blob-storage


【解决方案1】:

而不是将 true 作为值传递给 bool useFlatBlobListing 参数,如文档中的 here 传递 false。这将只为您提供容器中的顶级子文件夹和 blob

useFlatBlobListing(布尔值)

一个布尔值,指定是在平面列表中列出 Blob,还是按虚拟目录分层列出 Blob。

要进一步减少设置以仅列出顶级文件夹,您可以使用OfType

    public async Task<List<Cloud​Blob​Directory>> GetFullBlobsAsync()
    {
        var blobList = await Container.ListBlobsSegmentedAsync(string.Empty, false, BlobListingDetails.None, int.MaxValue, null, null, null);

        return (from blob in blobList
                             .Results
                             .OfType<CloudBlobDirectory>() 
                select blob).ToList();
    }

这将返回Cloud​Blob​Directory 实例的集合。它们反过来也提供了ListBlobsSegmentedAsync 方法,因此您可以使用该方法来获取该目录中的 blob。

顺便说一句,既然您并没有真正使用分段,为什么不使用比ListBlobsSegmentedAsync 更简单的ListBlobs 方法?

【讨论】:

  • 由于某种原因我找不到ListBlobs 方法。会不会是过时了?
  • 是这个:docs.microsoft.com/en-us/dotnet/api/… 可能在 .Net Core 中不可用?
  • 是的,在 .NET Core 中不可用。
【解决方案2】:

为了仅列出容器内的文件夹而不列出内容(对象),您可以将以下内容用于 Scala。这是获取子目录的通用方法,并且可以用于更复杂的结构,例如

Container  
|  
|  
____Folder 1  
|   ____Folder 11  
|   ____Folder 12  
|   |.  ____File 111.txt
|   |   
____Folder 2   
    ____Folder 21 
    ____Folder 22  

这里的前缀基本上是您希望找到其子目录的路径。确保将“/”分隔符添加到前缀中。

val container: CloudBlobContainer = blobClient.getContainerReference(containerName)
var blobs = container.listBlobs(prefix + '/' ,false, util.EnumSet.noneOf(classOf[BlobListingDetails]), null, null)  

在 listBlobs 函数中,第二个参数用于使用 FlatBlobListing,我们将其设置为 false,因为我们只需要子目录而不需要它们的内容。我们可以设置为空的其他参数。 Blob 将包含子目录列表。您可以通过遍历 blob 列表并调用 getUri 函数来获取 URL。

【讨论】:

    猜你喜欢
    • 2015-11-10
    • 2023-03-03
    • 2022-11-30
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 2020-10-09
    • 2019-06-28
    • 2020-03-27
    相关资源
    最近更新 更多