Uploading Files to Azure Blob Storage with .NET Core

In today's data-driven environment, businesses and applications generate a significant amount of data that needs to be stored securely and accessed efficiently. Azure Blob Storage offers a service that is not only highly available and secure but also scalable, making it an ideal solution for storing large volumes of unstructured data such as text, binary data, documents, and media files.

Recently, a client approached us with the requirement to integrate file storage into their application. They needed a solution that could handle the storage of various document types securely and ensure quick data retrieval. After evaluating several options, we decided that Azure Blob Storage would be the best fit due to its robustness, scalability, and integration capabilities with existing .NET applications.

Our client specifically needed to store PDF documents in a structured manner, and they wanted a simple yet efficient way to upload these documents to the cloud. The document we'll focus on in this tutorial is named "NikunjSatasiya.pdf," and it will be stored in a Blob Storage container named "Codingvila.com."

In this article, I will guide you through setting up a .NET Core application to upload files to Azure Blob Storage using Azure.Storage.Blobs library. By the end of this guide, you'll have a clear understanding of how to implement this functionality in a .NET Core application, ensuring you can meet similar client requirements with ease.

Before we dive into the implementation, make sure you have:

  • An active Azure subscription. If you don't have one, you can create an account for free.
  • Access to the Azure portal where you can create and manage your Azure Storage account.
  • The Azure Blob Storage container "Codingvila.com" is set up within your Storage account.
  • .NET Core SDK installed on your machine.

Let’s get into the setup and implementation process.

Step 1. Install Required Packages

To interact with Azure Blob Storage, the first step is to add the necessary NuGet package to your .NET Core project. Open your terminal and execute the following command in your project directory.

dotnet add package Azure.Storage.Blobs

This command installs the Azure Storage Blobs client library, which provides functionality for communicating with Blob Storage services.

Step 2. Configuration Setup

Configuration details such as your Azure Storage connection string should be stored securely and not hard-coded in your application. Add these details in your appsettings.json file.

{
  "AzureBlobStorage": {
    "ConnectionString": "your_azure_storage_connection_string",
    "ContainerName": "Codingvila.com"
  }
}

Replace "your_azure_storage_connection_string" with the actual connection string that you can find in the Azure portal under your storage account’s “Access keys” section.

Step 3. Creating the Blob Service

Now, create a service class named BlobService.cs to encapsulate the Azure Blob Storage operations. This class will handle the logic for uploading files.

using Azure.Storage.Blobs;
using System.IO;
using System.Threading.Tasks;
public class BlobService
{
    private readonly string _connectionString;

    public BlobService(string connectionString)
    {
        _connectionString = connectionString;
    }

    public async Task UploadFileAsync(string filePath)
    {
        var blobServiceClient = new BlobServiceClient(_connectionString);
        var blobContainerClient = blobServiceClient.GetBlobContainerClient("Codingvila.com");

        var fileName = Path.GetFileName(filePath);
        var blobClient = blobContainerClient.GetBlobClient(fileName);

        using var uploadFileStream = File.OpenRead(filePath);
        await blobClient.UploadAsync(uploadFileStream, overwrite: true);
        uploadFileStream.Close();

        System.Console.WriteLine($"File {fileName} uploaded successfully to container {blobContainerClient.Name}.");
    }
}

Step 4. Implementing File Upload in Your Application

Finally, integrate the BlobService into your main program or wherever it fits within the larger application. Here’s a simple implementation of the Program.cs file.

class Program
{
    static async Task Main(string[] args)
    {
        var connectionString = "your_azure_storage_connection_string"; // Ideally fetched from configuration
        var blobService = new BlobService(connectionString);

        string localFilePath = "path_to_your_file/NikunjSatasiya.pdf";

        await blobService.UploadFileAsync(localFilePath);
    }
}

Ensure you replace "your_azure_storage_connection_string" and "path_to_your_file/NikunjSatasiya.pdf" with your actual connection string and file path.

Here are some potential enhancements and considerations for your future development.

  • Security Enhancements: Implement Azure Managed Identities for Azure resources to secure your storage operations without storing credentials in your code.
  • Error Handling: Add comprehensive error handling around the upload process to manage exceptions and provide clear feedback for troubleshooting.
  • Automated Backups: Set up routine backups and lifecycle management policies to handle the retention and archiving of documents.
  • Access Management: Utilize Azure Active Directory (Azure AD) to manage and control access to the blobs based on user or group permissions.
  • Scalability Testing: Conduct load testing to ensure that your application can handle a large number of file uploads simultaneously without performance degradation.

By following this, you've taken a significant step towards integrating advanced cloud storage solutions into your applications. Azure Blob Storage, combined with .NET Core, offers a flexible and powerful platform to build applications that require extensive data storage capabilities. As you move forward, continue exploring Azure's full potential by integrating more of its services to enhance your application's performance, security, and scalability.

Feel free to adapt and expand upon this foundation as your project requirements grow. Whether you are developing a small application or a large-scale enterprise system, the principles covered here will serve as a valuable guide in your journey with Azure and .NET Core.

Summary

You have now successfully set up a .NET Core application that can upload files to Azure Blob Storage, meeting the client's requirements for a secure and scalable document storage solution. This implementation not only allows for the efficient handling of file uploads but also lays the groundwork for further expansion, such as adding features for file management and retrieval.

Incorporating Azure Blob Storage into your .NET Core applications can greatly enhance data handling capabilities, providing robustness through features like automated replication and data redundancy, which ensures high availability and data durability. The integration process is straightforward, thanks to the Azure.Storage.The Blobs library simplifies interactions with the Azure Blob service.


Codingvila
Codingvila is an educational website, developed to help tech specialists/beginners.