如何列出Azure blob存储中的子目录

时间:2014-11-11 14:38:41

标签: list azure subdirectory blobstorage

MS宣布像blob存储一样的目录,我试图像目录一样使用它。  用名字保存了一些blob:

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

我希望有可能枚举子目录,例如我有blobclient引用Common容器名称,我想获得子容器列表Type1, Type2, Type3。是否可以获取某些目录中的子目录列表。使用ListBlobs返回当前容器中的完整blob列表。

3 个答案:

答案 0 :(得分:13)

如果您想列出所有"子目录"在" Common \ Service1"目录你可以使用这样的东西:

    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);
    }

完整代码示例:

    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);
    }

这将为Type1,Type2和Type3目录输出Uri。

答案 1 :(得分:9)

b2zw2a's answer

为基础
  • 仅在使用@而非\时才需要/
  • ToList()之后不要链ListBlobs()ListBlobs()提供延迟加载并为您提供更好的性能。
  • 使用OfType<CloudBlobDirectory>()过滤掉您想要的类型

给你:

var directory = blobContainer.GetDirectoryReference("Common/Service1");
var folders = directory.ListBlobs().OfType<CloudBlobDirectory>();
foreach (var folder in folders)
{
    Console.WriteLine(folder.Uri);
}

答案 2 :(得分:-1)

var nameList=logoContainer.ListBlobs().Where(b => b as CloudBlobDirectory != null).Select(x => x.Uri + "").ToList();

通过使用此功能,您可以在单个查询中获取所有文件名。