c# - 如何使用 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)
如果一切都在本地运行,我基本上需要与运行相同的结果!有没有办法改进这个功能?
解决方案
也许您可以改进您的解决方案来检查 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;
我没有太多文件夹,所以最好仔细检查一下性能是否符合您的要求。
推荐阅读
- google-cloud-platform - 是否可以过滤 GCP Cloud SQL 复制中的某些列?
- r - 在 summarise_at() 中使用 n() 时出错
- java - 如何修复 JDBC 中的 SQLNonTransientConnectionException
- flask - 如何编写一个 api 来根据传递的索引获取表的记录?
- javascript - 如何在javascript中将此字符串“09-March-2018”转换为Unix时间戳?
- c# - 从基接口集合创建派生接口的通用集合
- laravel-6 - 未找到错误类“Illuminate\Support\Facades\Input” laravel v6.0.2
- openvino - OpenVINO 将 TF 模型转换为 IR 文件问题
- discord - Discord.js 中的临时 Bann 角色
- database - 删除表时间戳()时如何摆脱错误未知列updated_at