首页 > 解决方案 > 如何使用 c# 获取 Azure Blob 存储容器中现有目录的列表?

问题描述

C#我有一个使用Core .NET 2.2 框架顶部编写的控制台应用程序。

我正在尝试使用C# 库来获取容器内所有目录的列表。据我了解,Azure Blob 存储实际上并没有目录。相反,它会创建虚拟名称,使 Blob 看起来像Azure Blob Explorer等浏览器中容器内的文件夹

我使用以下代码存储我的文件

CloudBlockBlob blockBlob = container.GetBlockBlobReference("foldername/filename.jpg");

await blockBlob.UploadFromStreamAsync(stream);

所以我想在我的容器内选择一个不同的前缀列表,也就是文件夹名称。

因此,如果我有以下 blob“foldername1/file1.jpg”、“foldername1/file2.jpg”、“foldername1/file3.jpg”和“foldername2/file1.jpg”。我想返回“文件夹名 1”、“文件夹名 2”

如何从 Azure Blob 存储中获取不同前缀的列表?

更新

我试图从下面的评论中获得反馈,所以我想出了以下代码

public async Task<string[]> Directories(string path = null)
{
    int index = path == null ? 0 : path.Split('/', StringSplitOptions.RemoveEmptyEntries).Length;

    BlobContinuationToken token = null;
    List<string> directories = new List<string>();
    do
    {
        BlobResultSegment blobsListingResult = await ContainerFactory.Get().ListBlobsSegmentedAsync(path ?? string.Empty, true, BlobListingDetails.None, 5000, token, null, null);
        token = blobsListingResult.ContinuationToken;
        IEnumerable<IListBlobItem> blobsList = blobsListingResult.Results;
        foreach (var item in blobsList)
        {
            var blobName = (item as CloudBlob).Name;
            var blobParts = blobName.Split('/', StringSplitOptions.RemoveEmptyEntries);

            if (blobParts.Length <= index)
            {
                // At this point, we know that this not a directory inside the provided path directory
                continue;
            }

            directories.Add(blobParts[index]);
        }
    }
    while (token != null);

    return directories.Distinct().ToArray();
}

由于我在容器中有很多 blob,这需要很长时间,因为它几乎必须获取每个块才能获取目录列表。此外,这可能非常昂贵,因为每次调用此方法时我都必须读取每个 blob。

Directory.GetDirectories(path)如果一切都在本地运行,我基本上需要与运行相同的结果!有没有办法改进这个功能?

标签: c#azureazure-blob-storage

解决方案


也许您可以改进您的解决方案来检查 blob 项目的类型?

        var result = new List<string>();
        var directory = _blobContainer.GetDirectoryReference(relativeFilePath);

        if (directory.Equals(null))
            return result;

        var blobs = directory.ListBlobsSegmentedAsync(null).Result;

        foreach (var item in blobs.Results)
        {
            if (item.GetType() == typeof(CloudBlobDirectory)) 
            {
                result.Add(item.Uri.Segments.Last().Trim('/'));
            }
        }

        return result;

我没有太多文件夹,所以最好仔细检查一下性能是否符合您的要求。


推荐阅读