How to list subdirectories in Azure blob repository

MS has declared the directory as blob storage, and I'm trying to use it as directories. Keeping some drops by name:

Common\Service1\Type1\Object1 Common\Service1\Type1\Object2 Common\Service1\Type2\Object1 Common\Service1\Type2\Object2 Common\Service1\Type3\Object1 Common\Service1\Type3\Object2 Common\Service1\Type3\Object3 

I would like to be able to list subdirectories, for example. I have a blobclient associated with the Common container name, and I would like to get a list of Type1, Type2, Type3 . Is it possible to get a list of subdirectories in some directory. Using ListBlobs returns a complete list of blocks in the current container.

+5
source share
3 answers

If you want to list all the "subdirectories" in the "Common \ Service1" directory, you can use something like this:

  var directory = blobContainer.GetDirectoryReference(@"Common/Service1"); var folders = directory.ListBlobs().Where(b => b as CloudBlobDirectory != null).ToList(); foreach (var folder in folders) { Console.WriteLine(folder.Uri); } 

Full sample code:

  var random = new Random(); CloudStorageAccount storageAccount = CloudStorageAccount.DevelopmentStorageAccount; var cloudBlobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer blobContainer = cloudBlobClient.GetContainerReference("test-container"); blobContainer.CreateIfNotExists(); string[] objects = new[] { @"Common\Service1\Type1\Object1", @"Common\Service1\Type1\Object2", @"Common\Service1\Type2\Object1", @"Common\Service1\Type2\Object2", @"Common\Service1\Type3\Object1", @"Common\Service1\Type3\Object2", @"Common\Service1\Type3\Object3" }; foreach (var newObject in objects) { var newBlob = blobContainer.GetBlockBlobReference(newObject); var buffer = new byte[1024]; random.NextBytes(buffer); newBlob.UploadFromByteArray(buffer,0,buffer.Length); } var directory = blobContainer.GetDirectoryReference(@"Common/Service1"); var folders = directory.ListBlobs().Where(b => b as CloudBlobDirectory != null).ToList(); foreach (var folder in folders) { Console.WriteLine(folder.Uri); } 

This will result in Uri output for the Type1, Type2, and Type3 directory.

+7
source

Based on b2zw2a answer :

  • @ is only required when using \ , not / .
  • Do not ToList() after ListBlobs() . ListBlobs() provides lazy loading and will give you better performance.
  • Use OfType<CloudBlobDirectory>() to filter out only the type you need.

Providing you:

 var directory = blobContainer.GetDirectoryReference("Common/Service1"); var folders = directory.ListBlobs().OfType<CloudBlobDirectory>(); foreach (var folder in folders) { Console.WriteLine(folder.Uri); } 
+5
source
 var nameList=logoContainer.ListBlobs().Where(b => b as CloudBlobDirectory != null).Select(x => x.Uri + "").ToList(); 

Using this, you can get all the file names in one query.

0
source

Source: https://habr.com/ru/post/1206645/


All Articles