2016-06-07 44 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, ' '); 
} 
相關問題