如何使用 Azure.Storage.Blobs BlobClient 在 blob 目录路径中检索 blob?

How to retrieve blobs within a blob directory path using the Azure.Storage.Blobs BlobClient?

我没有在网上看到任何关于如何获取位于 BlobContainerClient.

中特定目录内的所有 blob 的示例

以前,我使用的是 Microsoft.Azure.Storage 包,但这些包已被弃用。我扫描目录中所有 blob 的旧代码是:

public async Task<void> ListAllBlobs(string path)
{
    var myContainer = await GetCloudBlobClientAsync();
    var directory = myContainer.GetDirectoryReference(path);
    var blobs = await directory.ListBlobsSegmentedAsync(true, BlobListingDetails.None, 
        blobSettings.MaxResult, null, null, null);
    var results = blobs.Results;

    foreach(CloudBlockBlob b in results)
    {
        // non-relevant code
    }
}

private async Task<CloudBlobContainer> GetCloudBlobClientAsync()
{
    var storageAccount = CloudStorageAccount.Parse(azureBlobStorageConnectionString);
    var blobClient = storageAccount.CreateCloudBlobClient();
    var container = blobClient.GetContainerReference(blobStorageSettings.ContainerName);

    if (!await container.ExistsAsync())
    {
        await container.CreateAsync();
    }

    return container;
}

基本上,我将上面的代码从 Microsoft.Azure.Storage 移到 Azure.Storage.Blobs

如果我要重新创建 ListAllBlobs(string path) 函数以使用 Azure.Storage.Blobs,我对如何设置容器然后根据传入的路径访问内部容器感到困惑 - 那么循环遍历该容器中存在的 blob。有人可以帮忙吗?

这是我目前的情况:

public async Task<void> ListAllBlobs(string path)
{
    var myContainer = await GetCloudBlobClientAsync();
    var directory = myContainer.GetBlobClient(path);

    // This doesn't work because I can't do 'GetBlobs' on the Client, only on the container.
    foreach(BlobItem blob in directory.GetBlobs(Blobtraits.None, BlobStates.None, string.Empty))
    {
        // more non-relevant code
    }
}

为了澄清,在上面的代码中,它不喜欢我在客户端而不是容器上调用 GetBlobs,但我无法传递到容器的路径.

试试这个...

static async Task GetBlobs()
{
    string connectionString = "<connection_string>";
    string containerName = "<container_name>";

    var blobContainerClient = new BlobContainerClient(connectionString, containerName);

    var blobs = blobContainerClient.GetBlobs(Azure.Storage.Blobs.Models.BlobTraits.All, Azure.Storage.Blobs.Models.BlobStates.All,
        "YourPrefix");

    foreach (var blob in blobs)
    {
        Console.WriteLine(blob.Name); 
    }
}

...对我有用。

你快到了。你仍然会在上面使用 BlobContainerClient and call GetBlobsAsync 方法。您错过的是您需要将 prefix 参数的值设置为 path.

所以你的代码应该是这样的:

var myContainer = await GetCloudBlobClientAsync();
var blobsListingResult = await myContainer.GetBlobsAsync(prefix=path);

更新

请尝试以下代码:

var myContainer = await GetCloudBlobClientAsync();
await foreach (BlobItem blob in myContainer.GetBlobsAsync(BlobTraits.None, BlobStates.None, path))
{
  names.Add(blob.Name);
}