Search code examples
c#.netazureazure-blob-storageazure-storage

How to get the count of files inside a certain folder of container in Azure Blob storage in C#


I'm working with Azure Blob Storage and need to count the number of files inside a specific folder within a blob container.
I already have the prefix (example - folder1) and the container name and just need the count of the files

Is there a way without having to read all the files. I'm using dotnet 8(C#)

Should i do somthing like this or is there a proper solution

    BlobServiceClient blobServiceClient = new BlobServiceClient("DefaultEndpointsProtocol=https;AccountName=hello;AccountKey=asaACVsfFefsdsdsfadJHGDZCJSCSNyessfsfsfsfsfsc==;EndpointSuffix=core.windows.net");
    int count = 0;
    var blobContainerClient = blobServiceClient.GetBlobContainerClient("mycontainer");
    var blobs = blobContainerClient.GetBlobsAsync(prefix:"folder1");
    
    await foreach (BlobItem blob in blobs)
    {
        count++;
    }


Solution

  • How to get the count of files inside a certain folder of container in Azure Blob storage in C#

    Unfortunately, Azure Blob Storage does not provide a direct API to count blobs in a folder without listing them.

    The approach requires iterating through the list of blobs returned by the GetBlobsAsync method, and your approach is also correct.

    Code:

    using System;
    using System.Threading.Tasks;
    using Azure.Storage.Blobs;
    using Azure.Storage.Blobs.Models;
    
    namespace AzureBlobStorageExample
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                string connectionString = "xx";
                string containerName = "result";
                string folderPrefix = "audio/";
    
                BlobContainerClient containerClient = new BlobContainerClient(connectionString, containerName);
    
                // Count the blobs in the folder
                int blobCount = await GetBlobCountAsync(containerClient, folderPrefix);
    
                Console.WriteLine($"Number of blobs in folder '{folderPrefix}': {blobCount}");
            }
            static async Task<int> GetBlobCountAsync(BlobContainerClient containerClient, string folderPrefix)
            {
                int count = 0;
    
                // Iterate through the blobs with the specified prefix
                await foreach (BlobItem blobItem in containerClient.GetBlobsAsync(prefix: folderPrefix))
                {
                    count++;
                }
    
                return count;
            }
        }
    }
    

    Output:

    Number of blobs in folder 'audio/': 3
    

    enter image description here

    Reference:

    List blobs with .NET - Azure Storage | Microsoft Learn