Azure blob storage download to stream returning "" asp.net
Solution 1
However I am not getting anything back but an empty string.
I test your supplied code on my side, it works correctly. I assume that the test blob content is empty in your case. We could trouble shooting with following ways:
1.please have a try to check the Length of memoryStream. If length equal 0 we could know that the blob content is empty.
using (var memoryStream = new MemoryStream())
{
blockBlob2.DownloadToStream(memoryStream);
var length = memoryStream.Length;
text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
}
2.We could upload a blob with content to container, we could do that with Azure portal or Microsoft Azure storage explorer easily. And please have a try test it with uploaded blob.
Solution 2
If you want to get the text from the blob, you can use DownloadTextAsync()
var text = await blockBlob2.DownloadTextAsync();
If you want to return file stream back to an API respoinse, you can use FileStreamResult which is IActionResult.
var stream = await blockBlob2.OpenReadAsync();
return File(stream, blockBlob2.Properties.ContentType, "name");
Hayden Passmore
I am a software developer that loves to create mobile apps (when the code is working) I have published apps for both android an iOS. Also at my current position I work on creating new components for our web app using .NET. Outside of programming I enjoy listening to music and the seeing outdoors.
Updated on December 21, 2020Comments
-
Hayden Passmore over 3 years
I am currently trying to download a file from Azure blob storage using the DownloadToStream method to download the contents of a blob as a text string. However I am not getting anything back but an empty string.
Here is my code that I use to connect to the azure blob container and retrieve the blob file.
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; }
I was following along this documentation however I cannot seem to get it to work. Any help would be greatly appreciated.