2017-09-26 58 views
0

我目前正試圖從Azure blob存儲使用DownloadToStream方法下載文件作爲文本字符串的內容。 但是我沒有收到任何東西,只是一個空字符串。Azure blob存儲下載到流返回「」asp.net

這是我用來連接到azure blob容器並檢索blob文件的代碼。

public static string DownLoadFroalaImageAsString(string blobStorageName, string companyID) 
    { 
     // Retrieve storage account from connection string. 
     CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
      CloudConfigurationManager.GetSetting("StorageConnectionString")); 

     // Create the blob client. 
     CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); 

     // Retrieve reference to a previously created container. 
     CloudBlobContainer container = blobClient.GetContainerReference(companyID.ToLower()); 

     //retrieving the actual filename of the blob 
     string removeString = "BLOB/"; 
     string trimmedString = blobStorageName.Remove(blobStorageName.IndexOf(removeString), removeString.Length); 

     // Retrieve reference to a blob named "trimmedString" 
     CloudBlockBlob blockBlob2 = container.GetBlockBlobReference(trimmedString); 

     string text; 
     using (var memoryStream = new MemoryStream()) 
     { 
      blockBlob2.DownloadToStream(memoryStream); 
      text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray()); 
     } 
     return text; 
    } 

我沿着this文件,但我似乎無法讓它工作。任何幫助將不勝感激。

回答

2

但是我沒有得到任何東西,只是一個空字符串。

我測試您提供的代碼在我身邊,它工作正常。我假設您的案例中測試blob內容爲空。我們可以通過以下方式排除故障:

1.請嘗試檢查memoryStream的長度。如果長度等於0,我們可以知道blob內容是空的。

using (var memoryStream = new MemoryStream()) 
{ 
    blockBlob2.DownloadToStream(memoryStream); 
    var length = memoryStream.Length; 
    text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray()); 
} 

2.我們可以上傳與內容容器斑點,我們可以做到這一點與Azure的門戶或Microsoft Azure storage explorer容易。請嘗試使用上傳的blob進行測試。

+0

謝謝!我在將文件上傳到blob存儲容器時遇到了問題,因此爲什麼我的代碼不會返回任何文件,因爲該文件不存在。 :-S –

+0

@HaydenPassmore就上傳問題而言:sourcestream(re)中的位置設置爲0?給了我很多次。 –

+0

@RickvandenBosch我遇到了我的流位置問題,謝謝。我今天早些時候發佈了一個問題[https://stackoverflow.com/questions/46418526/uploading-file-to-azure-blob-storage-then-sending-http-response-with-the-files-b] –