How to load list of Azure blob files recursively?

mikhail-t picture mikhail-t · May 16, 2015 · Viewed 16.7k times · Source

Azure blob files are stored in a plain list without any physical folder structure, but we can create virtual folders where each file's folder path is a part of its name.

It brings out another problem, how to retrieve a list of ALL files in virtual sub-folder, using only that folder's name?

Answer

Stopped Contributing picture Stopped Contributing · May 16, 2015

Actually, there's a simpler way to do that and it is available in the library itself. If you look at CloudBlobContainer.ListBlobs method, it accepts two parameters:

  1. prefix: This is the name of your directory. If it is a nested directory, you will need to specify the full path e.g. myfolder/mysubfolder.
  2. useFlatBlobListing: Setting this value to true will ensure that only blobs are returned (including inside any sub folders inside that directory) and not directories and blobs.

    var account = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
    var blobClient = account.CreateCloudBlobClient();
    var container = blobClient.GetContainerReference("blob-container-name");
    var blobs = container.ListBlobs(prefix: "container-directory", useFlatBlobListing: true);
    

You will get a list of all blobs belonging in the "container-directory" in blobs variable.