How to get size of Azure CloudBlobContainer
Asked Answered
C

2

7

I'm creating a .net wrapper service for my application that utilizes Azure Blob Storage as a file store. My application creates a new CloudBlobContainer for each "account" on my system. Each account is limited to a maximum amount of storage.

What is the simplest and most efficient way to query the current size (space utilization) of an Azure CloudBlobContainer`?

Corrientes answered 15/2, 2013 at 19:29 Comment(1)
Possible duplicate of Azure Storage container sizeMeaghan
C
14

FYI here's the answer. Hope this helps.

public static long GetSpaceUsed(string containerName)
{
    var container = CloudStorageAccount
        .Parse(ConfigurationManager.ConnectionStrings["StorageConnection"].ConnectionString)
        .CreateCloudBlobClient()
        .GetContainerReference(containerName);
    if (container.Exists())
    {
        return (from CloudBlockBlob blob in
                container.ListBlobs(useFlatBlobListing: true)
                select blob.Properties.Length
               ).Sum();
    }
    return 0;
}
Corrientes answered 12/3, 2013 at 16:14 Comment(2)
The answer seems to be quite old now. I want to ask if there is any better way found so far, to calculate the size of the Blob Container?Meaghan
ListBlobs method is no longer available in latest versions.Meaghan
M
4

As of version v9.x.x.x or greater of WindwosAzure.Storage.dll (from Nuget package), ListBlobs method is no longer available publicly. So the solution for applications targeting .NET Core 2.x+ would be like following:

BlobContinuationToken continuationToken = null;
long totalBytes = 0;
do
{
    var response = await container.ListBlobsSegmentedAsync(continuationToken);
    continuationToken = response.ContinuationToken;
    totalBytes += response.Results.OfType<CloudBlockBlob>().Sum(s => s.Properties.Length);
} while (continuationToken != null);
Meaghan answered 14/1, 2019 at 13:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.