2017-09-26 68 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] –