I need help with my code. The problem is that my code loads the entire file from the Azure storage account in memory before returning it to the user I want to return the file without consuming a lot of memory. The files can be everything from 5MB to a couple of GB but when the file is large all memory is consumed and the App Service crashes.
public async Task<IActionResult> GetFile(string blobName)
{
CloudBlockBlob blockBlob;
await using (MemoryStream memoryStream = new MemoryStream())
{
string blobstorageconnection = _configuration.GetValue<string>("blobstorage");
string blobContainer = _configuration.GetValue<string>("blobcontainer");
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(blobstorageconnection);
CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(blobContainer);
blockBlob = cloudBlobContainer.GetBlockBlobReference(blobName);
await blockBlob.DownloadToStreamAsync(memoryStream);
}
Stream blobStream = blockBlob.OpenReadAsync().Result;
return File(blobStream, blockBlob.Properties.ContentType, blockBlob.Name.Remove(0,9));
}
I summarize the solution as below.
When we download the blob's content form Azure Storage using less memory, please use the method OpenReadAsync
. It will return a readable stream then we can directly read blob content with the stream. So we do not need to provide MemoryStream
to save content. For more details, please refer to the document.