Build a File Manager App with .NET, Azure Blob Containers and Twilio SendGrid

October 16, 2024
Written by
Eman Hassan
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by

Build a File Manager App with .NET, Azure Blob Containers and Twilio SendGrid

Introduction

File management is one of the most common use cases in most modern applications, so it is important to learn how you can build simple file management features. In this tutorial, you'll learn how to create a web-based File Manager application using .NET. This application will integrate Azure Blob Storage for file handling, and Twilio SendGrid for email notifications. By the end, you'll have a functional app that allows users to upload, list, download, and delete files, with email notifications sent upon specific actions.

Prerequisites

In order to be successful in this tutorial, you will need the following:

Building the app

You will create a .NET web application that uploads and downloads files from an Azure Blob Container and sends email notifications when a file action occurs.

Setting up the application

If you are using Visual Studio Code, open terminal and run the following command to create your new project:

dotnet new mvc -n FileManager
cd FileManager

If you are using Visual Studio,click Create a new project. Search for asp.net mvc then select ASP.NET Core Web App (Model-View-Controller) as shown below. Click Next.

Create ASP.NET MVC web app

Enter the name “FileManager” for your project, then click Next. Select the latest .NET version. Keep the rest as defaults, then click Create.

Select .NET version

 

Creating an Azure Blob storage account

Sign in to the Azure portal, and click on Create a resource as shown below.

Create Azure resource

Search for “Storage account.” Select Microsoft’s storage account as shown below.

Microsoft storage account

Enter a name for your resource group and storage account. The name for your new storage account must be globally unique, but you can choose any name that fits the naming requirements in Azure. Keep the rest as defaults. Click Review + Create at the bottom, then click Create. It may take a few minutes for your new resource to deploy.

Create a blob container

Once your storage account has deployed successfully, access the storage account and navigate to Data Storage > Containers. Click the plus sign at the top as shown below to add a new blob container.

Add container

Give a name to the container, then click Create.

Add container's name

Navigate to Security + Networking > Access keys. Look for Key1, and copy the Connection string. You will need this for your application.

Get connection string

Integrating Azure Blob Storage into the .NET App

If you are using Visual Studio Code, run the following command in the terminal to install the Azure Blob Storage package.

dotnet add package Azure.Storage.Blobs

If you are using Visual Studio, go to the top menu. Click on Tools > NuGet Package Manager > Manage NuGet Packages for Solution as shown below.

Nuget package manager

Search for “Azure.Storage.Blobs” and install it to the project.by clicking Install. Small pop ups will show to apply dependencies and accept licenses. Click Apply, then Accept to install the package.

Install Azure Storage Blob

Open the file appSettings.json and add the connection string for the blob storage you created in Azure. Replace the placeholder with your connection string you copied earlier.

"ConnectionStrings": {
  "AzureBlobStorage": "Your_Azure_Storage_Connection_String"
},

Create a service to access your blob storage container

In Visual Studio, right click the project then click Add > New Folder. Add a folder named Services. Right click the Services folder and click Add > Class. Name your new class BlobService.cs.

Add the following code to the BlobService class for handling upload, list, download and delete operations with the Azure Blob Storage. Be sure the value in _containerName matches the name you gave your blob container.

using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
public class BlobService
{
    private readonly BlobServiceClient _blobServiceClient;
    private readonly string _containerName = "filesblob";
    public BlobService(IConfiguration configuration)
    {
        _blobServiceClient = new BlobServiceClient(configuration.GetConnectionString("AzureBlobStorage"));
    }
    public async Task UploadFileAsync(IFormFile file)
    {
        var containerClient = _blobServiceClient.GetBlobContainerClient(_containerName);
        var blobClient = containerClient.GetBlobClient(file.FileName);
        using (var stream = file.OpenReadStream())
        {
            await blobClient.UploadAsync(stream, new BlobHttpHeaders { ContentType = file.ContentType });
        }
    }
    public async Task<List<string>> ListFilesAsync()
    {
        var containerClient = _blobServiceClient.GetBlobContainerClient(_containerName);
        var items = new List<string>();
        await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
        {
            items.Add(blobItem.Name);
        }
        return items;
    }
    public async Task<Stream> DownloadFileAsync(string fileName)
    {
        var containerClient = _blobServiceClient.GetBlobContainerClient(_containerName);
        var blobClient = containerClient.GetBlobClient(fileName);
        var response = await blobClient.DownloadAsync();
        return response.Value.Content;
    }
    public async Task DeleteFileAsync(string fileName)
    {
        var containerClient = _blobServiceClient.GetBlobContainerClient(_containerName);
        var blobClient = containerClient.GetBlobClient(fileName);
        await blobClient.DeleteIfExistsAsync();
    }
}

Register the BlobService in the Program.cs file by adding the following code under the first two lines of code in the file.

builder.Services.AddSingleton<BlobService>();

Setting Up Twilio SendGrid

There are a few more mandatory steps you’ll need to complete in your Twilio SendGrid’s account:

  1. Verifying your Email
  2. Setting up 2-Factor Authentication
  3. Verifying your Domain

Once you’ve completed the above steps, you’ll need to create a new API Key with restricted access. On the Restricted Access tab, be sure your API Key is set to allow Email Sending access. Give your API key a name, and click Create + View. Keep this key somewhere safe as you will need it in the subsequent steps, and SendGrid will not show it again.

Add the API key, sender email and sender name in your appSettings.json file as shown below. and Replace the placeholders with your actual API key and verified sender information.

"SendGrid": {
   "ApiKey": "Your_SendGrid_API_Key",
   "SenderEmail": "your_verified_sender_email@example.com",
   "SenderName": "Your Name"
 },

Integrating Twilio SendGrid into the .NET App

If you are using Visual Studio Code, run the following command in the terminal to install the SendGrid package.

dotnet add package SendGrid

If you are using Visual Studio, open the NuGet Package Manager and install “SendGrid.” Apply and accept dependencies and license when prompted.

Install SendGrid

In the Services folder, add a new class called EmailService.cs. Replace the code in this file with the following code.

using SendGrid;
using SendGrid.Helpers.Mail;
public class EmailService
{
    private readonly string _apiKey;
    private readonly string _senderEmail;
    private readonly string _senderName;
    public EmailService(IConfiguration configuration)
    {
        _apiKey = configuration["SendGrid:ApiKey"];
        _senderEmail = configuration["SendGrid:SenderEmail"];
        _senderName = configuration["SendGrid:SenderName"];
    }
    public async Task SendEmailAsync(string recipientEmail, string subject, string message)
    {
        var client = new SendGridClient(_apiKey);
        var from = new EmailAddress(_senderEmail, _senderName);
        var to = new EmailAddress(recipientEmail);
        var msg = MailHelper.CreateSingleEmail(from, to, subject, message, message);
        await client.SendEmailAsync(msg);
    }
}

Register the EmailService by adding the following code to the Program.cs file under the top 3 lines of code.

builder.Services.AddSingleton<EmailService>();

Building the File Manager UI

Right click the Controller folder then click Add > Controller > MVC Controller - Empty. Give your new file the name FilesController.cs. Replace the code with the following code adding the index page action and the file operations actions. Replace recipient@example.com with the email address you want to send notifications to. You will have to do this for both the upload and delete tasks in the code.

using Microsoft.AspNetCore.Mvc;
public class FilesController : Controller
{
    private readonly BlobService _blobService;
    private readonly EmailService _emailService;
    public FilesController(BlobService blobService, EmailService emailService)
    {
        _blobService = blobService;
        _emailService = emailService;
    }
    public async Task<IActionResult> Index()
    {
        var files = await _blobService.ListFilesAsync();
        return View(files);
    }
    [HttpPost]
    public async Task<IActionResult> Upload(IFormFile file)
    {
        if (file != null)
        {
            await _blobService.UploadFileAsync(file);
            // Send email notification
            await _emailService.SendEmailAsync(
                "recipient@example.com",
                "File Uploaded",
                $"File {file.FileName} has been uploaded.");
            return RedirectToAction("Index");
        }
        return View("Index");
    }
    public async Task<IActionResult> Download(string fileName)
    {
        var stream = await _blobService.DownloadFileAsync(fileName);
        return File(stream, "application/octet-stream", fileName);
    }
    public async Task<IActionResult> Delete(string fileName)
    {
        await _blobService.DeleteFileAsync(fileName);
        // Send email notification
        await _emailService.SendEmailAsync(
            "recipient@example.com",
            "File Deleted",
            $"File {fileName} has been deleted.");
        return RedirectToAction("Index");
    }
}

Create UI Views

In the Views folder, create a new folder named Files. Right click the Files folder, then click Add > View > Empty view. Name your file Index.cshtml, then replace the code with the following code:

@model List<string>
<h2>File Manager</h2>
<form asp-action="Upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <button type="submit">Upload</button>
</form>
<table>
    <thead>
        <tr>
            <th>File Name</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var fileName in Model)
        {
            <tr>
                <td>@fileName</td>
                <td>
                    <a asp-action="Download" asp-route-fileName="@fileName">Download</a> |
                    <a asp-action="Delete" asp-route-fileName="@fileName">Delete</a>
                </td>
            </tr>
        }
    </tbody>
</table>

In Program.cs find the app.MapControllerRoute code. Replace it with the following code to configure the default page to the file manager’s page.

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Files}/{action=Index}/{id?}");

Testing the C# application

If you are using Visual Studio Code, run the following command in the terminal to run the application then navigate to the localhost specified in the run output.

dotnet run

If you are using Visual Studio, run the application by clicking on the green play button in the top of the Visual Studio window as shown below.

Run the application

Then browse the localhost port shown in the popup debug window. You will see a web interface that allows you to upload and download files from Azure.

Debugging window

Try uploading and downloading files, then check to see if you received an email.

Keep in mind that, when you publish this application, anyone browsing the app can see and access the uploaded files unless you implement security like authentication and user access profiles.
File manager UI

Check the email specified in your code. The email you receive should look like the one shown below.

File manager notification

Extending your C# SendGrid application

You've successfully built a File Manager application using .NET, integrated with Azure Blob Storage for file handling and Twilio SendGrid for email notifications. This application serves as a solid foundation for more complex file management systems, and you can extend it by adding features like user authentication, file sharing, and more.

If you want to continue to build out this application, here are a few options to consider:

  • Enhance Security: Implement authentication and authorization.
  • Add Logging: Use logging frameworks to track application behavior.
  • Improve UI: Enhance the user interface with Bootstrap or other CSS frameworks.
  • Handle Errors: Add proper error handling and validation.

You can find the entire code for the finished application here.

Eman Hassan, a dedicated software engineer, prioritizes innovation, cutting-edge technologies, leadership, and mentorship. By providing AI tools for text processing in regexmy.com and developer advocate as a service in advocatek.com, she finds joy in both learning and sharing expertise with the community. Explore more on her Medium profile: https://emhassan.medium.com.