Search code examples
c#azureazure-storage-account

Unable to get bloblist from a subdirectory in Storage Account


I would like to list all blobs from a subdirectory for example images/nature in a storage account. I am using this c# code to achieve my aim:

string storageConnectionString = Environment.GetEnvironmentVariable("BlobConnection", EnvironmentVariableTarget.Process);
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(@"images/nature");

This code doesn't work for me. Do you have any idea, how can I do this job?

Following code works fine if all blobs are in root folder:

 string storageConnectionString = Environment.GetEnvironmentVariable("BlobConnection", EnvironmentVariableTarget.Process);
 CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
 CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
 CloudBlobContainer container = blobClient.GetContainerReference(@"images");

Solution

  • Please try the following code:

    string storageConnectionString = Environment.GetEnvironmentVariable("BlobConnection", EnvironmentVariableTarget.Process);
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = blobClient.GetContainerReference(@"images");
    var blobs = container.ListBlobs("nature", true);
    

    This should list blobs inside "nature" folder and all folders beneath that.

    Essentially the issue was with the following line of code:

    CloudBlobContainer container = blobClient.GetContainerReference(@"images/nature");
    

    Azure Blob Storage basically has 2 level hierarchy - container and blobs. The folders there are virtual and essentially prefix that you put in a blob's name.

    What I have done in my code is listing the blobs from the container the name of which starts with a prefix ("nature" in your example).