Azure Blob Storage - Upload/Download/Delete File(s) Using .NET 5

Today in this article, we will see how to upload/download and delete the files in the cloud using Azure blob storage using ASP.Net Core 5.0 Web API.
 
Prerequisites
Let's perform all the basic operations like,
  1. Create an Azure storage account and blob container
  2. Getting the Access keys (Connection string)
  3. Create a web API Project (.Net 5.0)
  4. Connect to Azure Storage account
  5. Upload file to Azure Blob Storage
  6. Download file from  Azure Blob Storage
  7. Delete Files

Create an Azure storage account and blob container

 
Open the Azure portal and choose the Storage Account under the Azure Services.
 
Click on the + New button and it will take us to a new page to create a storage account.
 
Azure Blob Storage - Upload/Download/Delete File(s) Using .NET 5
 
After clicking on create a new storage account the first thing we are going to choose is the subscription you have, next create/select resource group after that, we are going to enter the Storage account name as “newfilestorage” next select the location whichever is right for you for this demo, I am going to choose “(US) East US” location. Next, we are selecting Performance options, here we have Standard Storage and Premium storage option we are going to select “Standard ” for this demo. Next comes your account type, we are going to choose “General-purpose v2” and in replication, we are going to choose “Geo-redundant storage (GRS)” and last option access tier we going to choose “Hot storage” at last click on review + create button.
 
Azure Blob Storage - Upload/Download/Delete File(s) Using .NET 5
After clicking on the Review + create here we can see the validation passed status and along with the review page with all the options which we had opted for and then click on create a button at the bottom to create a storage account.
 
Azure Blob Storage - Upload/Download/Delete File(s) Using .NET 5
 
Storage account 
 
Azure Blob Storage - Upload/Download/Delete File(s) Using .NET 5
 

Create a blob container under the storage account

 
To store the actual documents or files we need a blob container under the same storage account. Let's create a new blob container. Open the newly created storage account and under the left side options, you will find the named Container click on that where it gives us an option to create a new container.
 
Azure Blob Storage - Upload/Download/Delete File(s) Using .NET 5
 
Provide the name for the new container, choose the access level, and click on the create button at the bottom of the page. 
 
Azure Blob Storage - Upload/Download/Delete File(s) Using .NET 5

Getting the Access keys (Connection string)

 
Now here comes the main picture after the creation of the blob container, to incorporate the Azure storage account in the project we need to get the Access keys in communicating our project with our Azure storage account.
 
Access keys
 
Created by default when we set up the storage account.
 
Azure Blob Storage - Upload/Download/Delete File(s) Using .NET 5
From this screen, we are going to copy the Connection string (key 1).
 

Create a Web API Project (.Net 5)

 
Open the Visual Studio and chose the ASP.Net Core Web API and once after that choose the .Net 5.0 template from the dropdown it will create a project under the .Net 5 target framework.
 
Install the package which will communicate with the Azure Storage account,
 
Azure Blob Storage - Upload/Download/Delete File(s) Using .NET 5
 

Connect to Azure Storage account 

 
Here we are going to add the connection string and as well as blob container name to the appsettings.json file with the key name BlobConnectionString &  BlobContainerName and we need to pass the connection string and container name which we have copied from Access Key.
 
appsettings.json 
  1. {  
  2.     "Logging": {  
  3.         "LogLevel": {  
  4.             "Default""Information",  
  5.             "Microsoft""Warning",  
  6.             "Microsoft.Hosting.Lifetime""Information"  
  7.         }  
  8.     },  
  9.     "AllowedHosts""*",  
  10.     "BlobConnectionString""*Your Connection string*",  
  11.     "BlobContainerName""*Your container name*"  
  12. }   
After adding the keys, Now we are going to create a FileController (API) and injecting the IConfiguration for accessing the keys from the appsettings.json file.
 
FileController.cs
 
After creating the controller we are going to add the constructor for it for injecting the Iconfiguration dependency in order to fetch the values,
  1. using System.Collections.Generic;  
  2. using System.IO;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. namespace UploadAndDownload_AzureBlobStorage.Controllers {  
  6.     [Route("api/[controller]")]  
  7.     [ApiController]  
  8.     public class FileController: ControllerBase {  
  9.         private readonly IConfiguration _configuration;  
  10.         public FileController(IConfiguration configuration) {  
  11.             _configuration = configuration;  
  12.         }  
  13.     }  
  14. }   
Next, we are going to add a post method where we are going to use UploadFromStreamAsync to upload bytes.
 
In the Post method, you see the IFormFile interface as input which will get file details that are posted, then the first thing we are going to get is the connection string (“BlobConnectionString“) from the appsettings.json file using IConfiguration.
 
Next, we are going to retrieve the storage account from the connection string, after that we are going to create a blob client, we are going to use cloudBlobClient to Retrieve a reference to a container.
 
Then to retrieve posted file information, we are going to use files.OpenReadStream and copy them to a memory stream and then finally we are going to get the byte array of it to pass the UploadFromStreamAsync method.
 
Upload File [Post]method
  1. [HttpPost(nameof(UploadFile))]  
  2. public async Task < IActionResult > UploadFile(IFormFile files) {  
  3.     string systemFileName = files.FileName;  
  4.     string blobstorageconnection = _configuration.GetValue < string > ("BlobConnectionString");  
  5.     // Retrieve storage account from connection string.    
  6.     CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(blobstorageconnection);  
  7.     // Create the blob client.    
  8.     CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient();  
  9.     // Retrieve a reference to a container.    
  10.     CloudBlobContainer container = blobClient.GetContainerReference(_configuration.GetValue < string > ("BlobContainerName"));  
  11.     // This also does not make a service call; it only creates a local object.    
  12.     CloudBlockBlob blockBlob = container.GetBlockBlobReference(systemFileName);  
  13.     await using(var data = files.OpenReadStream()) {  
  14.         await blockBlob.UploadFromStreamAsync(data);  
  15.     }  
  16.     return Ok("File Uploaded Successfully");  
  17. }   
Download File [Post] method
 
To download the file from the blob container we need to pass the filename as parameter so that the filename will check and get back with the actual file from the container.
  1. [HttpPost(nameof(DownloadFile))]  
  2. public async Task < IActionResult > DownloadFile(string fileName) {  
  3.     CloudBlockBlob blockBlob;  
  4.     await using(MemoryStream memoryStream = new MemoryStream()) {  
  5.         string blobstorageconnection = _configuration.GetValue < string > ("BlobConnectionString");  
  6.         CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(blobstorageconnection);  
  7.         CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();  
  8.         CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(_configuration.GetValue < string > ("BlobContainerName"));  
  9.         blockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);  
  10.         await blockBlob.DownloadToStreamAsync(memoryStream);  
  11.     }  
  12.     Stream blobStream = blockBlob.OpenReadAsync().Result;  
  13.     return File(blobStream, blockBlob.Properties.ContentType, blockBlob.Name);  
  14. }   
Delete File [Delete] Method
  1. [HttpDelete(nameof(DeleteFile))]  
  2. public async Task < IActionResult > DeleteFile(string fileName) {  
  3.     string blobstorageconnection = _configuration.GetValue < string > ("BlobConnectionString");  
  4.     CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(blobstorageconnection);  
  5.     CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();  
  6.     string strContainerName = _configuration.GetValue < string > ("BlobContainerName");  
  7.     CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(strContainerName);  
  8.     var blob = cloudBlobContainer.GetBlobReference(fileName);  
  9.     await blob.DeleteIfExistsAsync();  
  10.     return Ok("File Deleted");  
  11. }   
Now let's run the application and upload the file to Azure blob storage through Swagger
 
Azure Blob Storage - Upload/Download/Delete File(s) Using .NET 5
 
Let's see the file get uploaded to the Azure blob container. Open the storage account and click on the container and open the container where we will find all the uploaded files and their related information.
 
Azure Blob Storage - Upload/Download/Delete File(s) Using .NET 5
 
Download File
 
Azure Blob Storage - Upload/Download/Delete File(s) Using .NET 5
 
Delete File
 
Azure Blob Storage - Upload/Download/Delete File(s) Using .NET 5
 
Now let's go back to the blob container and see where the file gets deleted.
 
Azure Blob Storage - Upload/Download/Delete File(s) Using .NET 5
 
Source Code - Git Hub Repo
 
Thank you for reading, please let me know your questions, thoughts, or feedback in the comments section. I appreciate your feedback and encouragement.
keep learning....!


Similar Articles