Nlabs.FileService 9.0.0

dotnet add package Nlabs.FileService --version 9.0.0                
NuGet\Install-Package Nlabs.FileService -Version 9.0.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Nlabs.FileService" Version="9.0.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Nlabs.FileService --version 9.0.0                
#r "nuget: Nlabs.FileService, 9.0.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Nlabs.FileService as a Cake Addin
#addin nuget:?package=Nlabs.FileService&version=9.0.0

// Install Nlabs.FileService as a Cake Tool
#tool nuget:?package=Nlabs.FileService&version=9.0.0                

Nlabs.FileService

Overview

Nlabs.FileService is a library for handling file operations in .NET 9, including saving files to the server, uploading to FTP, and converting files to byte arrays for database storage. This library is designed to simplify file management in .NET applications and supports saving and deleting files both on the server and via FTP.

Dependency

This library requires .NET 9.

Installation

To install Nlabs.FileService, use the following command:

dotnet add package Nlabs.FileService

Usage Guide

IoC Configuration and Usage of FileService This WebAPI project manages static files (such as files in the wwwroot directory) using the Nlabs.FileService package. To utilize this package, configure dependency injection (DI) in your Program.cs file and provide the necessary settings.

Step 1: Adding Dependencies to IoC Container In your Program.cs file, use the AddFileService method to configure the IFileHostEnvironment interface, which registers the necessary dependencies in the IoC container:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddFileService(builder.Environment.WebRootPath);

Saving Files to the Server

To save a file on the server, specify the file path and call the FileSaveToServer method:

string filePath = "./Files/";
string fileName = FileService.FileSaveToServer(file, filePath);

Saving Files to FTP

To save a file on an FTP server, create a FileSaveToFtpModel instance with FTP credentials and then use the FileSaveToFtpAsync method:

FileSaveToFtpModel fileSaveToFtpModel = new("ftp.yourftpserver.com", "userName", "password", 21);
string fileName = await FileService.FileSaveToFtpAsync(file, fileSaveToFtpModel);

Saving Files to Database as Byte Array

To save a file as a byte array for database storage, use the FileConvertByteArrayToDatabase method:

byte[] fileByteArray = FileService.FileConvertByteArrayToDatabase(file);

Deleting Files on the Server

To delete a file on the server, use the FileDeleteToServer method with the file path:

string path = "./Files/" + fileName;
FileService.FileDeleteToServer(path);

Deleting Files on FTP

To delete a file on an FTP server, create a FileSaveToFtpModel instance with FTP credentials and then use the FileDeleteToFtpAsync method:

FileSaveToFtpModel fileSaveToFtpModel = new("ftp.yourftpserver.com", "userName", "password", 21);
await FileService.FileDeleteToFtpAsync(fileName, fileSaveToFtpModel);

Example Usage in a Layered Architecture

If you are using a layered architecture, you can inject IFileHostEnvironment in your handlers or services to manage file paths dynamically.

Example Handler Code:

internal sealed class MyCommandHandler : IRequestHandler
{
    private readonly IFileHostEnvironment _fileHostEnvironment;

    public MyCommandHandler(IFileHostEnvironment fileHostEnvironment)
    {
        _fileHostEnvironment = fileHostEnvironment;
    }

    public async Task Handle(MyCommand command)
    {
        var fullPath = Path.Combine(_fileHostEnvironment.WebRootPath, "Files", "file.jpeg");
        FileService.FileDeleteToServer(fullPath);
        // Additional logic here
    }
}

FileService

FileService provides methods for managing files on both the server and FTP. Key methods include:

Saving a File to the Server

public static string FileSaveToServer(IFormFile file, string filePath)
{
    var fileFormat = file.FileName.Substring(file.FileName.LastIndexOf('.')).ToLower();
    var fileName = Guid.NewGuid().ToString() + fileFormat;
    var fullPath = Path.Combine(filePath, fileName);

    using (var stream = new FileStream(fullPath, FileMode.Create))
    {
        file.CopyTo(stream);
    }

    return fileName;
}

Converting File to Byte Array for Database Storage

public static byte[] FileConvertByteArrayToDatabase(IFormFile file)
{
    using (var memoryStream = new MemoryStream())
    {
        file.CopyTo(memoryStream);
        return memoryStream.ToArray();
    }
}

Deleting a File from the Server

public static void FileDeleteToServer(string path)
{
    if (File.Exists(path))
    {
        File.Delete(path);
    }
}

Deleting a File on FTP

This method uses TcpClient to manually send FTP commands for file deletion:

public static async Task FileDeleteToFtpAsync(string fileName, FileSaveToFtpModel fileSaveToFtpModel)
{
    var ftpAddress = fileSaveToFtpModel.FtpAddress.Replace("ftp://", "").Replace("ftps://", "");
    int port = fileSaveToFtpModel.Port;

    using (var client = new TcpClient())
    {
        await client.ConnectAsync(ftpAddress, port);
        using (var networkStream = client.GetStream())
        using (var reader = new StreamReader(networkStream, Encoding.ASCII))
        using (var writer = new StreamWriter(networkStream, Encoding.ASCII) { AutoFlush = true })
        {
            await reader.ReadLineAsync();
            await writer.WriteLineAsync($"USER {fileSaveToFtpModel.UserName}");
            await reader.ReadLineAsync();
            await writer.WriteLineAsync($"PASS {fileSaveToFtpModel.Password}");
            await reader.ReadLineAsync();
            await writer.WriteLineAsync($"DELE {fileName}");

            var response = await reader.ReadLineAsync();
            if (response == null || !response.StartsWith("250"))
            {
                throw new Exception($"Failed to delete file: {response}");
            }

            await writer.WriteLineAsync("QUIT");
            await reader.ReadLineAsync();
        }
    }
}

Conclusion

The Nlabs.FileService library simplifies file management in .NET 9 applications by providing methods for saving files to both servers and FTP, deleting files, and converting files to byte arrays for database storage. This library is designed to be flexible, allowing integration in various .NET project structures and architectures.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
9.0.0 39 11/14/2024
8.0.7 127 6/27/2024
8.0.6 92 6/27/2024