如何获取具有子目录级别(n级)的Blob容器中的所有blob?

时间:2015-05-22 11:26:24

标签: c# azure blobs

尝试使用ListBlobsSegmentedAsync方法, 但是这只返回主父目录级别的blob ..

但我需要从所有n级子目录中一次性获取整个blob列表。

BlobContinuationToken continuationToken = null;
bool useFlatBlobListing = true;
BlobListingDetails blobListingDetails = BlobListingDetails.None;
int maxBlobsPerRequest = 500;
var blobOptions = new BlobRequestOptions (true );

do
 {
    var listingResult = await cbDir.ListBlobsSegmentedAsync(useFlatBlobListing, blobListingDetails, maxBlobsPerRequest, continuationToken, null, null);
    continuationToken = listingResult.ContinuationToken;
    srcBlobList.AddRange(listingResult.Results);
 } while (continuationToken != null);

2 个答案:

答案 0 :(得分:11)

使用此ListBlobsSegmentedAsync方法的覆盖:https://msdn.microsoft.com/en-us/library/dn434672.aspx,并确保为 true 传递 useFlatBlobListing 参数。这将列出所有子目录中的所有blob。

<强>更新

这是我使用的代码,它返回该子文件夹中的blob以及该子文件夹中的所有子文件夹。

    /// <summary>
    /// Code to fetch blobs from "temp" folder inside "blah" blob container.
    /// </summary>
    private static void GetFilesInSubfolder()
    {
        var account = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
        var blobClient = account.CreateCloudBlobClient();
        var container = blobClient.GetContainerReference("blah");
        var directory = container.GetDirectoryReference("temp");
        var result = directory.ListBlobsSegmented(true, BlobListingDetails.None, 500, null, null, null);
        var blobs = result.Results;
    }

答案 1 :(得分:3)

ListBlobsSegmentedAsync方法有2个重载,其中包含 useFlatBlobListing 参数。这些重载接受7或8个参数,我在您的代码中计为6。由于参数太多,您可以使用named arguments使代码更易于理解。

以下代码已在.NET Core中成功测试。

BlobContinuationToken blobContinuationToken = null;
do
{
    var resultSegment = await cloudBlobContainer.ListBlobsSegmentedAsync(prefix: null,
                                                                         useFlatBlobListing: true, 
                                                                         blobListingDetails: BlobListingDetails.None,
                                                                         maxResults: null,
                                                                         currentToken: blobContinuationToken,
                                                                         options: null,
                                                                         operationContext: null);
    // Get the value of the continuation token returned by the listing call.
    blobContinuationToken = resultSegment.ContinuationToken;
    foreach (IListBlobItem item in resultSegment.Results)
    {
        Console.WriteLine(item.Uri);
    }
} while (blobContinuationToken != null); // Loop while the continuation token is not null.

此代码来自Microsoft的storage-blobs-dotnet-quickstart存储库。