2016-04-22 60 views
0

我正在研究從Azure Blob中讀取數據並將該數據保存到對象中的項目。我目前遇到問題。現在我的代碼的設置方式 - 如果沒有虛擬文件夾存在,它將讀取容器中的所有.txt數據。如何判斷Azure容器是否有虛擬文件夾/目錄?

但是,如果在Azure容器中存在虛擬文件夾結構 我的代碼將出錯,並顯示NullExceptionReference。我的想法是做一個if檢查,看看是否有虛擬文件夾出現在Azure容器內,如果這樣執行//some code。有沒有辦法判斷是否存在虛擬文件夾?


ReturnBlobObject()

private List<Blob> ReturnBlobObject(O365 o365) 
    { 
     List<Blob> listResult = new List<Blob>(); 
     string textToFindPattern = "(\\/)"; 
     string fileName = null; 
     string content = null; 

     //Loop through all Blobs and split the container form the file name. 
     foreach (var blobItem in o365.Container.ListBlobs(useFlatBlobListing: true)) 
     { 
      string containerAndFileName = blobItem.Parent.Uri.MakeRelativeUri(blobItem.Uri).ToString(); 
      string[] subString = Regex.Split(containerAndFileName, textToFindPattern); 

      //subString[2] is the name of the file. 
      fileName = subString[2]; 
      content = ReadFromBlobStream(o365.Container.GetBlobReference(subString[2])); 

      Blob blobObject = new Blob(fileName, content); 

      listResult.Add(blobObject); 
     } 

     return listResult; 
    } 

ReadFromBlobStream

private string ReadFromBlobStream(CloudBlob blob) 
    { 
     Stream stream = blob.OpenRead(); 
     using (StreamReader reader = new StreamReader(stream)) 
     { 
      return reader.ReadToEnd(); 
     } 
    } 

回答

0

我能夠通過重構我的代碼來解決這個問題。而不是使用正則表達式 - 這是返回一些非常奇怪的行爲,我決定退後一步,並認爲這個問題。以下是我提出的解決方案。

ReturnBlobObject()

private List<Blob> ReturnBlobObject(O365 o365) 
    { 
     List<Blob> listResult = new List<Blob>(); 

     //Loop through all Blobs and split the container form the file name. 
     foreach (var blobItem in o365.Container.ListBlobs(useFlatBlobListing: true)) 
     { 
      string fileName = blobItem.Uri.LocalPath.Replace(string.Format("/{0}/", o365.Container.Name), ""); 
      string content = ReadFromBlobStream(o365.Container.GetBlobReference(fileName)); 

      Blob blobObject = new Blob(fileName, content); 

      listResult.Add(blobObject); 
     } 

     return listResult; 
    } 
相關問題