Azure File Share Storage Implementation Using .NET Core 6 Web API

In this article, we are going to discuss the introduction of azure file share and step-by-step implementation using .NET Core 6 Web API.

Agenda

  • Introduction
  • Benefits
  • Azure File Share Configuration
  • Step-by-step implementation of File share storage using .NET Core 6 Web API

Prerequisites

  • Visual Studio 2022
  • .NET Core 6
  • Azure Account

Introduction

  • Azure file share is used to deploy and mounted concurrently by cloud or on-premises deployments.
  • Azure file share offers storage on the cloud using standard SMB protocol.

Azure File Share Storage implementation using .NET Core 6 Web API

  • The Server Message Block (SMB) is the network file share protocol that helps us to read and write files.
  • File share can be accessed from Windows, Linux, and macOS.
  • NFS File share is accessible from Linux or macOS.

Benefits

  • Easy to configure and manage
  • Shared access between multiple VMs and Server Machine
  • Easy to use and managed by Azure CLI and Cmdlets

Azure File Share Configuration

Step 1

Open the Azure portal

Step 2

Search storage account and create the same.

Step 3

Open the storage account and click on “File Shares” and create a new file share.

Azure File Share Storage implementation using .NET Core 6 Web API

Azure File Share Storage implementation using .NET Core 6 Web API

Step 4

Here we can see the file share which we created earlier and all the files which we are going to upload we can find over here.

Azure File Share Storage implementation using .NET Core 6 Web API

Step 5

Also, open the access keys section in the storage account and copy and save the connection string which we use inside our web application.

Azure File Share Storage implementation using .NET Core 6 Web API

Step-by-step implementation of File share storage using .NET Core 6 Web API

Step 1

Create a new Web API project.

Azure File Share Storage implementation using .NET Core 6 Web API

Step 2

Configure a new project.

Azure File Share Storage implementation using .NET Core 6 Web API

Step 3

Provide additional information.

Azure File Share Storage implementation using .NET Core 6 Web API

Step 4

Install the following NuGet Packages.

Azure File Share Storage implementation using .NET Core 6 Web API

Step 5

Project Structure.

Azure File Share Storage implementation using .NET Core 6 Web API

Step 6

Create a File Details class.

namespace AzureFileShareDemo
{
    public class FileDetails
    {
        public IFormFile FileDetail { get; set; }
    }
}

Step 7

Next, create IFileShare and FileShare inside repositories.

IFileShare.cs

namespace AzureFileShareDemo.Repositories
{
    public interface IFileShare
    {
        Task FileUploadAsync(FileDetails fileDetails);
        Task FileDownloadAsync(string fileShareName);
    }
}

FileShare.cs

using Azure;
using Azure.Storage.Files.Shares;
using Azure.Storage.Files.Shares.Models;

namespace AzureFileShareDemo.Repositories
{
    public class FileShare : IFileShare
    {
        private readonly IConfiguration _config;

        public FileShare(IConfiguration config)
        {
            _config = config;
        }

        public async Task FileUploadAsync(FileDetails fileDetails)
        {
            // Get the configurations and create share object
            ShareClient share = new ShareClient(_config.GetConnectionString("default"), _config.GetValue<string>("FileShareDetails:FileShareName"));

            // Create the share if it doesn't already exist
            await share.CreateIfNotExistsAsync();

            // Check the file share is present or not
            if (await share.ExistsAsync())
            {
                // Get a reference to the sample directory
                ShareDirectoryClient directory = share.GetDirectoryClient("FileShareDemoFiles");

                // Create the directory if it doesn't already exist
                await directory.CreateIfNotExistsAsync();

                // Ensure that the directory exists
                if (await directory.ExistsAsync())
                {
                    // Get a reference to a file and upload it
                    ShareFileClient file = directory.GetFileClient(fileDetails.FileDetail.FileName);

                    // Check path
                    var filesPath = Directory.GetCurrentDirectory() + "/files";
                    var fileName = Path.GetFileName(fileDetails.FileDetail.FileName);
                    var filePath = Path.Combine(filesPath, fileName);

                    using (FileStream stream = File.OpenRead(filePath))
                    {
                        file.Create(stream.Length);
                        file.UploadRange(
                            new HttpRange(0, stream.Length),
                            stream);
                    }
                }
            }
            else
            {
                Console.WriteLine($"File is not upload successfully");
            }
        }

        public async Task FileDownloadAsync(string fileShareName)
        {
            ShareClient share = new ShareClient(_config.GetConnectionString("default"), _config.GetValue<string>("FileShareDetails:FileShareName"));
            ShareDirectoryClient directory = share.GetDirectoryClient("FileShareDemoFiles");
            ShareFileClient file = directory.GetFileClient(fileShareName);

            // Check path
            var filesPath = Directory.GetCurrentDirectory() + "/files";
            if (!System.IO.Directory.Exists(filesPath))
            {
                Directory.CreateDirectory(filesPath);
            }

            var fileName = Path.GetFileName(fileShareName);
            var filePath = Path.Combine(filesPath, fileName);

            // Download the file
            ShareFileDownloadInfo download = file.Download();
            using (FileStream stream = File.OpenWrite(filePath))
            {
                await download.Content.CopyToAsync(stream);
            }
        }
    }
}

Step 8

Add the file share name and connection string inside the appsettings.json file.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "FileShareDetails": {
    "FileShareName": "jdlearningfileshare"
  },
  "ConnectionStrings": {
    "default": ""
  }
}

Step 9

Register a service inside the Program class.

using AzureFileShareDemo.Repositories;
using FileShare = AzureFileShareDemo.Repositories.FileShare;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddScoped < IFileShare, FileShare > ();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

Step 10

Next, create a new File Controller.

using AzureFileShareDemo.Repositories;
using Microsoft.AspNetCore.Mvc;

namespace AzureFileShareDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FilesController : ControllerBase
    {
        private readonly IFileShare fileShare;

        public FilesController(IFileShare fileShare)
        {
            this.fileShare = fileShare;
        }

        /// <summary>
        /// upload file
        /// </summary>
        /// <param name="fileDetail"></param>
        /// <returns></returns>
        [HttpPost("Upload")]
        public async Task<IActionResult> UploadFile([FromForm] FileDetails fileDetail)
        {
            if (fileDetail.FileDetail != null)
            {
                await fileShare.FileUploadAsync(fileDetail);
            }
            return Ok();
        }

        /// <summary>
        /// download file
        /// </summary>
        /// <param name="fileDetail"></param>
        /// <returns></returns>
        [HttpPost("Download")]
        public async Task<IActionResult> DownloadFile(string fileName)
        {
            if (fileName != null)
            {
                await fileShare.FileDownloadAsync(fileName);
            }
            return Ok();
        }
    }
}

Step 11

Finally, run the project and use API endpoints using Swagger UI.

Azure File Share Storage implementation using .NET Core 6 Web API

Step 11

Upload a few files using Swagger UI

Azure File Share Storage implementation using .NET Core 6 Web API

Step 12

Next, open the azure file share, and inside that, you can find the files that we uploaded.

Azure File Share Storage implementation using .NET Core 6 Web API

This is all about an azure file share.

GitHub Link

https://github.com/Jaydeep-007/AzureFileShareDemo

Conclusion

Here we discussed the basics of azure file share and the file upload and download functionality by using .NET Core Web API.

Happy Learning!


Similar Articles