Azure Blob Storage With ASP.NET Core

Azure Blob Storage With ASP.NET Core

This blog will show you how to create a container and files in Azure Blob Storage.

You must first install the Azure.Storage.Blobs package.

Install-Package Azure.Storage.Blobs

Create a container in Azure Blob Storage

Let's start by learning how to create a container in Azure Blob Storage. A connection string is required for this. Go to Azure Blob Storage -> Access keys for that. There are two key values there. Choose the first option. The connection string will be concealed. When you click the show button on the right side, the connection string will be revealed. You can now copy the connection string.

Azure Blob Storage With ASP.NET Core

A code snippet for creating a container in Azure Storage is provided below. The connection string has been set up here. The instance of BlobContainerClient has been created. Using the BlobContainerClient instance, determine whether the container name exists or not, and if not, create a new container with the given name.

The container name must adhere to the following guidelines.

  1. The container name must have between 3 and 63 characters.
  2. It should begin with a letter or a number, and it should only contain letters, numbers, and the hyphen.
  3. Lowercase letters must be used in blob container names.
HomeController.cs
using Azure.Storage.Blobs;

public IActionResult CreateConatiner(string conatinerNameText)
{
    string connectionString = "DefaultEndpointsProtocol=https;AccountName=customerstorage;AccountKey=RgQcRTzDCaseT3DBa71JhpCZqbNLlsfbkK+9DnOq85++wlWxuhK1g;EndpointSuffix=core.windows.net";

    BlobContainerClient container = new(connectionStringconatinerNameText);

    if (!container.Exists())
    {
        container.Create();

        ViewBag.CreateMsg = "Container Successfully Created";
    }
    else
    {
        ViewBag.CreateMsg = "Container Already Exist";
    }

    return View("Index");
}

The view code is as follows. It receives container names and sends them to the controller.

Index.cshtml
<form method="post" asp-controller="Home" asp-action="CreateConatiner">

  Enter container name: <input id="conatinerNameText" name="conatinerNameText" type="text" />
  <br />
  <input type="submit" value="Create Container" />
  <div style="color:green">@ViewBag.CreateMsg</div>
</form>

The above code produced the following result. In this case, the sample container was created in Azure storage.

Azure Blob Storage With ASP.NET Core

Upload File/Object to Azure Blob Storage Container

The code below assists in uploading the file to the Azure Blob Storage Container. The GetBlobClient() method appends blob names to the end of Uri to create a new BlobClient object. The code then determines whether or not the files already exist in the container. If the file already exists, the message "File Already Exist" is displayed; otherwise, the file is uploaded to an Azure storage container.

public IActionResult Upload(IFormFile uploadFile)
{
    string connectionString = "DefaultEndpointsProtocol=https;AccountName=customerstorage;AccountKey=RgQcRTzDCaseT3DBa71JhpCZqbNLlsfbkK+9DnOq85++wlWxuhK1g;EndpointSuffix=core.windows.net";

    BlobContainerClient container = new(connectionString"sample");

    BlobClient blob = container.GetBlobClient(uploadFile.FileName);

    if (!blob.Exists())
    {
        using (var memoryStream = new MemoryStream())
        {
            uploadFile.CopyTo(memoryStream);
            memoryStream.Position = 0;
            var result = blob.Upload(memoryStream);
        }

        ViewBag.CreateMsg = "File Uploaded Successfully";
    }
    else
    {
        ViewBag.CreateMsg = "File Already Exist";
    }

    return View("Index");
}

The code for a razor page is as follows. To upload the file, it has a file upload and submit button element.

<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Upload">
  <div class="form-group">
      <div class="col-md-10">
          <p>Upload File:</p>
          <input type="file" name="uploadFile" />
      </div>
  </div>
  <div class="form-group">
      <div class="col-md-10">
          <input type="submit" value="Upload" />
      </div>
  </div>
      <div style="color:green">@ViewBag.CreateMsg</div>
</form>

The image below is the result of the above code. It demonstrates how the file was uploaded to the Azure storage container.

Azure Blob Storage With ASP.NET Core

List Azure Blob Container Files

The following code shows how to get a list of file names from an Azure blob container. Using the GetBlobs() method, the following code retrieves all of the files from the sample container. It collects the names of the blob files using a foreach loop and sends them to the view to display.

public IActionResult Index()
{
    string connectionString = "DefaultEndpointsProtocol=https;AccountName=customerstorage;AccountKey=RgQcRTzDCaseT3DBa71JhpCZqbNLlsfbkK+9DnOq85++wlWxuhK1g;EndpointSuffix=core.windows.net";

    BlobContainerClient container = new(connectionString"sample");
    List<stringblobList = new List<string>();
    var blobs = container.GetBlobs();

    foreach (BlobItem blob in blobs)
    {
       
blobList.Add(blob.Name);
    }

    return View(blobList);
}

The following is a razor page code that displays the name of the blob files using a table.

@model List<string>

<table class="table">
    <thead>
        <tr>
            <th scope="col">File Name</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
            <td>@item</td>
            </tr>
        }
    </tbody>
</table>

The above code produced the following result. It displays a list of blob files found in the 'sample' Azure container.

Azure Blob Storage With ASP.NET Core

Download Azure Blob Container File

The code below shows how to download an Azure blob container file. The code below downloads the file that was downloaded via MemoryStream. The file type was then determined using the file extension method, and the file was downloaded.

public IActionResult Download(string fileName)
{
    string connectionString = "DefaultEndpointsProtocol=https;AccountName=customerstorage;AccountKey=RgQcRTzDCaseT3DBa71JhpCZqbNLlsfbkK+9DnOq85++wlWxuhK1g;EndpointSuffix=core.windows.net";

    // sample is a name of the container
    BlobClient blob = new (connectionString"sample"fileName);
    MemoryStream ms = new ();
    blob.DownloadTo(ms);

    var ext = Path.GetExtension(fileName);
    string contentType = "";
    if (ext == ".pdf")
    {
        contentType = "application/pdf";
    }

    return File(ms.ToArray(), contentTypefileName);
}

The code for a razor page is as follows. The download link for the files has been added here.

@model List<string>

<table class="table">
    <thead>
        <tr>
            <th scope="col">File Name</th>
            <th scope="col">Download</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
            <td>@item</td>
            <td><a href='Home/download?fileName=@item'>Download</a></td>
            </tr>
        }
    </tbody>
</table>

The following is a output of the above code

Download Azure Blob Storage file With ASP.NET Core

Delete Azure Blob Container File

The code examples below show how to delete a file from the Azure Blob Storage Container. The code checks whether or not the 'sample' container and the given file name exist. The file is then deleted if it exists.

public IActionResult Delete(string fileName)
{
    string connectionString = "DefaultEndpointsProtocol=https;AccountName=customerstorage;AccountKey=RgQcRTzDCaseT3DBa71JhpCZqbNLlsfbkK+9DnOq85++wlWxuhK1g;EndpointSuffix=core.windows.net";

    BlobContainerClient container = new BlobContainerClient(connectionString"sample");

    if (container.Exists())
    {
        BlobClient blob = container.GetBlobClient(fileName);

        if (blob.Exists())
        {
            blob.DeleteIfExists();
            ViewBag.CreateMsg = "File Deleted Successfully";
        }
        else
        {
            ViewBag.CreateMsg = "File Not Available";
        }
    }

    // Code to get a list of files
    …
    …
    …
    return View("Index"blobList);
}

The code for a razor page is as follows. To delete the files, a delete link has been added here.

@model List<string>
  <div style="color:green">@ViewBag.CreateMsg</div>
  <table class="table">
      <thead>
          <tr>
              <th scope="col">File Name</th>
              <th scope="col">Download</th>
              <th scope="col">Delete</th>
          </tr>
      </thead>
      <tbody>
          @foreach (var item in Model)
          {
              <tr>
                  <td>@item</td>
                  <td><a href='Home/download?fileName=@item'>Download</a></td>
                  <td><a href='Home/delete?fileName=@item'>Delete</a></td>
              </tr>
          }
      </tbody>
  </table>

The image below is the result of the above code. When the user clicked the delete link, the file was deleted from the Azure storage container.

Delete Azure Blob Storage files With ASP.NET Core

I hope this helps you. Keep coding.

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

Creating a C# Azure Function with Visual Studio: Step-by-Step Guide

Exploring EventCallback in Blazor: Building Interactive Components