在Azure.Storage.Blobs
版本中12.6.0
,可以通过以下方式完成:
static void Main(string[] args)
{
BlobServiceClient client = new BlobServiceClient(connectionString);
GetContainersSize(client, connectionString, null, null).Wait();
}
//-------------------------------------------------
// List containers
//-------------------------------------------------
async static Task<ConcurrentDictionary<string, long>> GetContainersSize(BlobServiceClient blobServiceClient,
string connectionString,
string prefix,
int? segmentSize)
{
string continuationToken = string.Empty;
var sizes = new ConcurrentDictionary<string, long>();
try
{
do
{
// Call the listing operation and enumerate the result segment.
// When the continuation token is empty, the last segment has been returned
// and execution can exit the loop.
var resultSegment =
blobServiceClient.GetBlobContainersAsync(BlobContainerTraits.Metadata, prefix, default)
.AsPages(continuationToken, segmentSize);
await foreach (Azure.Page<BlobContainerItem> containerPage in resultSegment)
{
foreach (BlobContainerItem containerItem in containerPage.Values)
{
BlobContainerClient container = new BlobContainerClient(connectionString, containerItem.Name);
var blobs = container.GetBlobsAsync().AsPages(continuationToken);
await foreach(var blobPage in blobs)
{
var blobPageSize = blobPage.Values.Sum(b => b.Properties.ContentLength.GetValueOrDefault());
sizes.AddOrUpdate(containerItem.Name, blobPageSize, (key, currentSize) => currentSize + blobPageSize);
}
}
// Get the continuation token and loop until it is empty.
continuationToken = containerPage.ContinuationToken;
}
} while (continuationToken != string.Empty);
return sizes;
}
catch (RequestFailedException e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
throw;
}
}