Introduction
In this article, we will understand how to retrieve, upload, and delete azure blob storage file. I strongly recommend you read or go through below articles if you are new to azure storage account. I have used.NET core 6 MVC for this article.
Creating a New Project in Visual Studio 2022
Start Visual Studio software and select Create a new project.
In the Create a new project dialog, select ASP.NET Core Web App (Model-View Controller) > Next.
In the Configure your new project dialog, enter BlobStoragerFileRtrieveUploadDeleteCore6MVC_Demo for Project name. It's important to name the project BlobStoragerFileRtrieveUploadDeleteCore6MVC_Demo. The capitalization needs to match each namespace when code is copied. Select Next.
In the Additional information dialog, select .NET 6.0 (Long-term support). Select Create
The Visual Studio project 2022 will now generate the structure for the selected application. In this example, we are using ASP.Net MVC so we can create a controller to write the code, or so we can use the existing controller. There you can enter the code and build/run the application.
How to Install the WindowsAzure.Storage Library through NuGet Package Manager
The Visual Studio software provides the Nuget Package manager option to install the package directly to the solution.
In Visual Studio Select Tools > NuGet Package Manager > Manage NuGet Packages for the solution. The below screenshot shows how to open the Nuget Package Manager.
Search for the specific package WindowsAzure.Storage using the search box on the upper left. Select a package from the list to display its information, enable the Install button and a version-selection drop-down, as shown in the below screenshot. The NuGet package will be installed for your project and reference will be added, as seen in the screenshot below.
In the above image, we can see the list of the related search items. We need to select the required option to install the package to the solution.
Get Connection String
In azure portal select create storage select Access Kays from right panel. Check for connection string click on show copy your connection from here.
Get Container Name
In azure portal select create storage select Containers from right panel. Check container name and copy it.
On "Visual Studio Solution Explorer" select a file appsettings.json. Open this file and “Add” connection string that you learn from above.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"BlobConnectionString": "DefaultEndpointsProtocol=https;AccountName=firststorageaccountdemo;AccountKey=2UIIgYivwB/6mLJFsbGmo8ofPuShjzyFimyYBspb0fbDcuQxLlbpWHhV8t+1fEK7VRLCEfdFZmTn+AStcMy2sw==;EndpointSuffix=core.windows.net",
"BlobContainerName": "blob-container"
}
On "Visual Studio Solution Explorer" Right-click the Models folder > Add > Class. Name the file BlobStorage.cs
using System.ComponentModel.DataAnnotations;
namespace BlobStoragerFileRtrieveUploadDeleteCore6MVC_Demo.Models {
public class BlobStorage {
[Display(Name = "File Name")]
public string FileName {
get;
set;
}
[Display(Name = "File Size")]
public string FileSize {
get;
set;
}
public string Modified {
get;
set;
}
}
}
On "Visual Studio Solution Explorer" Create a folder BlobStorageServices andin that add an Interface IBlobStorageService.cs
using BlobStoragerFileRtrieveUploadDeleteCore6MVC_Demo.Models;
namespace BlobStoragerFileRtrieveUploadDeleteCore6MVC_Demo.BlobStorageServices
{
public interface IBlobStorageService
{
Task<List<BlobStorage>> GetAllBlobFiles();
Task UploadBlobFileAsync(IFormFile files);
Task DeleteDocumentAsync(string blobName);
}
}
Now create a class BlobStorageService and implement IBlobStorageService
using BlobStoragerFileRtrieveUploadDeleteCore6MVC_Demo.Models;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage;
namespace BlobStoragerFileRtrieveUploadDeleteCore6MVC_Demo.BlobStorageServices
{
public class BlobStorageService : IBlobStorageService
{
private readonly string _storageConnectionString;
private readonly string _storageContainerName;
public BlobStorageService(IConfiguration configuration)
{
_storageConnectionString = configuration.GetValue<string>("BlobConnectionString");
_storageContainerName = configuration.GetValue<string>("BlobContainerName");
}
public async Task<List<BlobStorage>> GetAllBlobFiles()
{
try
{
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(_storageConnectionString);
// Create the blob client.
CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(_storageContainerName);
CloudBlobDirectory dirb = container.GetDirectoryReference(_storageContainerName);
BlobResultSegment resultSegment = await container.ListBlobsSegmentedAsync(string.Empty,
true, BlobListingDetails.Metadata, 100, null, null, null);
List<BlobStorage> fileList = new List<BlobStorage>();
foreach (var blobItem in resultSegment.Results)
{
// A flat listing operation returns only blobs, not virtual directories.
var blob = (CloudBlob)blobItem;
fileList.Add(new BlobStorage()
{
FileName = blob.Name,
FileSize = Math.Round((blob.Properties.Length / 1024f) / 1024f, 2).ToString(),
Modified = DateTime.Parse(blob.Properties.LastModified.ToString()).ToLocalTime().ToString()
});
}
return fileList;
}
catch (Exception)
{
throw;
}
}
public async Task UploadBlobFileAsync(IFormFile files)
{
try
{
byte[] dataFiles;
// Retrieve storage account from connection string.
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(_storageConnectionString);
// Create the blob client.
CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
// Retrieve a reference to a container.
CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(_storageContainerName);
BlobContainerPermissions permissions = new BlobContainerPermissions
{
PublicAccess = BlobContainerPublicAccessType.Blob
};
string systemFileName = files.FileName;
await cloudBlobContainer.SetPermissionsAsync(permissions);
await using (var target = new MemoryStream())
{
files.CopyTo(target);
dataFiles = target.ToArray();
}
// This also does not make a service call; it only creates a local object.
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(systemFileName);
await cloudBlockBlob.UploadFromByteArrayAsync(dataFiles, 0, dataFiles.Length);
}
catch (Exception)
{
throw;
}
}
public async Task DeleteDocumentAsync(string blobName)
{
try
{
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(_storageConnectionString);
CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(_storageContainerName);
var blob = cloudBlobContainer.GetBlobReference(blobName);
await blob.DeleteIfExistsAsync();
}
catch (Exception)
{
throw;
}
}
}
}
On "Visual Studio Solution Explorer" select a file Program.cs “Add” below service.
builder.Services.AddScoped<IBlobStorageService, BlobStorageService>();
On "Visual Studio Solution Explorer" in controllers folder select HomeController and “Add” below code.
using BlobStoragerFileRtrieveUploadDeleteCore6MVC_Demo.BlobStorageServices;
using Microsoft.AspNetCore.Mvc;
namespace BlobStoragerFileRtrieveUploadDeleteCore6MVC_Demo.Controllers
{
public class HomeController : Controller
{
private readonly IBlobStorageService _blobStorage;
public HomeController(IBlobStorageService blobStorage)
{
_blobStorage = blobStorage;
}
public async Task<IActionResult> Index()
{
return View(await _blobStorage.GetAllBlobFiles());
}
[HttpGet]
public IActionResult Upload()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Upload(IFormFile files)
{
await _blobStorage.UploadBlobFileAsync(files);
return RedirectToAction("Index");
}
public async Task<IActionResult> Delete(string blobName)
{
await _blobStorage.DeleteDocumentAsync(blobName);
return RedirectToAction("Index", "Home");
}
}
}
On "Visual Studio Solution Explorer" in Views folder open Home folder select Index.cshtml file and paste below code.
@model IEnumerable<BlobStoragerFileRtrieveUploadDeleteCore6MVC_Demo.Models.BlobStorage>
@{
ViewData["Title"] = "Index";
}
<h2 class="text-uppercase text-center">List of blob files</h2>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
<i class="fa-solid fa-circle-plus"></i> Upload New File
</button>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Upload">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Blob Storage File Upload</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label> Select File </label>
<input class="form-control" name="files" multiple="multiple" type="file" />
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<input class="btn btn-success" type="submit" value="Upload" />
</div>
</form>
</div>
</div>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th>FileName</th>
<th>FileSize</th>
<th>Modified</th>
<th>Action(s)</th>
</tr>
</thead>
<tbody>
@foreach (var data in Model)
{
<tr>
<td>@data.FileName</td>
<td>@data.FileSize</td>
<td>@data.Modified</td>
<td> <a href="/Home/[email protected]" class="btn btn-danger"><i class="fa-solid fa-trash"></i></a></td>
</tr>
}
</tbody>
</table>
Run your project ctrl+F5
Conclusion
In this article, we have learned how to upload file to azure blob storage, retrieve uploaded files and delete file using ASP.NET Core6 MVC. I hope you enjoyed the article. Happy coding