2016-06-07 65 views
0

我正在处理Azure Blob存储实例中特定目录中包含的大量数据,并且我只想获取某个目录中所有内容的大小。我知道如何获得整个容器的大小,然而它逃避了我如何指定目录本身来从中提取数据。如何获取Azure Blob存储容器中特定目录的大小?

我当前的代码如下所示:

private static long GetSizeOfBlob(CloudStorageAccount storageAccount, string nameOfBlob) 
    { 
     CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); 

     // Finding the container 
     CloudBlobContainer container = blobClient.GetContainerReference(nameOfBlob); 

     // Iterating to get container size 
     long containerSize = 0; 
     foreach (var listBlobItem in container.ListBlobs(null, true)) 
     { 
      var blobItem = listBlobItem as CloudBlockBlob; 
      containerSize += blobItem.Properties.Length; 
     } 

     return containerSize; 
    } 

如果我指定的BLOB容器像“democontainer/testdirectory”,我得到一个400错误(我想因为它是一个目录,使用反斜杠将允许我导航到我想要遍历的目录)。任何帮助将不胜感激。

+0

如果你真的想离开这里为未来的探索者,发布你的解决方案*答案*,而不是*编辑*的问题。 –

+0

@DavidMakogon哎呀,这是新的。抱歉! –

回答

0

我已经解决了自己的问题,但在离开这里未来蔚蓝Blob存储探险家。

您实际上需要在拨打container.ListBlobs(prefix: 'somedir', true)时提供前缀,以便访问涉及的特定目录。这个目录是在您访问的容器名称之后出现的任何内容。

0

您需要先获得CloudBlobDirectory,然后才能从那里开始工作。

例如:

var directories = new List<string>(); 
var folders = blobs.Where(b => b as CloudBlobDirectory != null); 

foreach (var folder in folders) 
{ 
    directories.Add(folder.Uri); 
} 
0
private string GetBlobContainerSize(CloudBlobContainer contSrc) 
    { 
     var blobfiles = new List<string>(); 
     long blobfilesize = 0;  
     var blobblocks = new List<string>(); 
     long blobblocksize = 0; 

     foreach (var g in contSrc.ListBlobs()) 
     { 
      if (g.GetType() == typeof(CloudBlobDirectory)) 
      { 
       foreach (var file in ((CloudBlobDirectory)g).ListBlobs(true).Where(x => x as CloudBlockBlob != null)) 
       { 
        blobfilesize += (file as CloudBlockBlob).Properties.Length; 
        blobfiles.Add(file.Uri.AbsoluteUri); 
       } 
       } 
       else if (g.GetType() == typeof(CloudBlockBlob)) 
       { 
        blobblocksize += (g as CloudBlockBlob).Properties.Length; 
        blobblocks.Add(g.Uri.AbsoluteUri); 
       } 
      } 

      string res = string.Empty; 
      if (blobblocksize > 0) res += "size: " + FormatSize(blobblocksize) + "; blocks: " + blobblocks.Count(); 
      if (!string.IsNullOrEmpty(res) && blobfilesize > 0) res += "; "; 
      if (blobfilesize > 0) res += "size: " + FormatSize(blobfilesize) + "; files: " + blobfiles.Count(); 
      return res; 
} 

private string FormatSize(long len) 
{ 
    string[] sizes = { "B", "KB", "MB", "GB", "TB" }; 
    int order = 0; 
    while (len >= 1024 && order < sizes.Length - 1) 
    { 
     order++; 
     len = len/1024; 
    } 
    return $"{len:0.00} {sizes[order]}".PadLeft (9, ' '); 
}