SmartFileKit 1.0.1

There is a newer version of this package available.
See the version list below for details.
dotnet add package SmartFileKit --version 1.0.1
                    
NuGet\Install-Package SmartFileKit -Version 1.0.1
                    
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="SmartFileKit" Version="1.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="SmartFileKit" Version="1.0.1" />
                    
Directory.Packages.props
<PackageReference Include="SmartFileKit" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add SmartFileKit --version 1.0.1
                    
#r "nuget: SmartFileKit, 1.0.1"
                    
#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.
#:package SmartFileKit@1.0.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=SmartFileKit&version=1.0.1
                    
Install as a Cake Addin
#tool nuget:?package=SmartFileKit&version=1.0.1
                    
Install as a Cake Tool

SmartFileKit

SmartFileKit is a lightweight, high-performance, and security-focused .NET library designed for secure file validation, file signature (magic byte) verification, MIME type detection, and file classification. Built with reliability, performance, and zero external dependencies in mind, it is ideal for enterprise applications and secure file upload scenarios.

NuGet Version License: MIT


๐Ÿš€ Key Features

  • File Size Formatting & Calculations: Convert bytes dynamically to KB, MB, GB, and TB units, perform arithmetic operations and comparisons, and format output with configurable decimal precision using CultureInfo.InvariantCulture.
  • MIME & Category Detection: Automatically identify MIME types and high-level categories (Image, Document, Spreadsheet, Presentation, Archive, Video, Audio, Executable, etc.) for over 40 popular file formats.
  • Content-Based Magic Bytes Verification: Inspect leading header bytes (up to 4096 bytes) rather than relying solely on file extensions. This prevents extension-spoofing attacks (e.g., detecting .exe binaries disguised as .jpg or arbitrary ZIP packages renamed to .docx).
  • Filename Sanitization: Clean user-supplied filenames by converting Turkish characters to their English equivalents, removing invalid filesystem chars, mitigating directory traversal attacks, and preventing Windows reserved device name collisions (CON, PRN, NUL, etc.).
  • Fluent Validation API: A highly readable builder syntax for size ranges, allowed/blocked extensions, allowed/blocked MIME types, allowed/blocked categories, and active signature validation.
  • Zero-Dependency & Low-Allocation: Completely self-contained library utilizing array and stream buffer pooling to maximize throughput in high-scale ASP.NET Core APIs.

๐Ÿ“ฆ Installation

Install via the .NET CLI:

dotnet add package SmartFileKit

Or via the Package Manager Console:

Install-Package SmartFileKit

๐Ÿ› ๏ธ Usage Examples

1. File Size Formatting & Extensions

The FileSize struct supports comparison and arithmetic operators, and decimal formatting is culture-invariant (always uses a dot .).

using SmartFileKit;
using SmartFileKit.Domain;

// Define sizes fluently
FileSize maxLimit = 5.MB();
FileSize minLimit = 500.KB();

// Convert numeric types to FileSize
long bytesCount = 1048576 * 3; // 3 MB
FileSize size = bytesCount.ToFileSize();

Console.WriteLine(size.ToString());    // Output: "3.00 MB" (Default precision is 2)
Console.WriteLine(size.ToString(1));   // Output: "3.0 MB"

// Comparisons and arithmetic
if (size < maxLimit)
{
    FileSize totalSpace = size + 10.MB();
    Console.WriteLine($"Total Space: {totalSpace}"); // Output: "13.00 MB"
}

2. Filename Sanitization & Dixin Traversal Protection

Normalize names before saving them to disk. This converts special characters, strips path manipulation tricks, and avoids reserving OS filenames.

using SmartFileKit;

// Turkish character normalization
string fileName1 = FileName.Sanitize("รถzel rapor (2026).pdf");
// Output: "ozel rapor (2026).pdf"

// Directory traversal protection
string fileName2 = FileName.Sanitize("../../../etc/passwd");
// Output: "etc_passwd"

string fileName3 = FileName.Sanitize("..\\..\\windows\\system32.dll");
// Output: "windows_system32.dll"

// Windows Reserved name resolution
string fileName4 = FileName.Sanitize("CON.txt");
// Output: "_CON.txt"

3. MIME and Category Detection

Detect the true file format using Stream or byte[]. Seekable streams are automatically rewound back to their original position after signature inspection.

using System.IO;
using SmartFileKit;
using SmartFileKit.Domain;

using (var stream = File.OpenRead("upload.dat"))
{
    FileFormatInfo format = FileType.GetFormat(stream);
    
    if (format != null)
    {
        Console.WriteLine($"Extension: {format.Extension}"); // e.g. ".jpg"
        Console.WriteLine($"MIME:      {format.MimeType}");  // e.g. "image/jpeg"
        Console.WriteLine($"Category:  {format.Category}");  // e.g. "Image"
    }

    // Direct helper checks
    bool isImage = FileType.IsImage(stream);
    bool isArchive = FileType.IsArchive(stream);
}

4. Fluent File Validation

Enforce security and constraints during file uploads. Spoofing checks are active by default to compare extension declarations against actual headers.

using System;
using SmartFileKit.Validation;
using SmartFileKit.Domain;

byte[] fileData = GetUploadedFileBytes(); // E.g., user uploaded "avatar.jpg" but content is EXE!

var result = FileValidator.Validate(fileData, "avatar.jpg")
    .MaxSize(5.MB())
    .AllowedExtensions(".jpg", ".png")
    .AllowedCategories(FileCategory.Image)
    .Execute();

if (!result.IsValid)
{
    Console.WriteLine("Validation Failed!");
    foreach (var error in result.Errors)
    {
        Console.WriteLine($"- {error}");
    }
    // Output:
    // - File signature mismatch detected (Spoofing). File extension suggests '.jpg' (Image), but actual content matches '.exe' (Executable).
    // - File category 'Executable' is not allowed.
}

// Or throw a FileValidationException directly:
try
{
    FileValidator.Validate(fileData, "avatar.jpg")
        .MaxSize(5.MB())
        .AllowedExtensions(".jpg")
        .ThrowIfInvalid();
}
catch (FileValidationException ex)
{
    Console.WriteLine(ex.Message);
}

๐Ÿ›ก๏ธ Security Best Practices

  1. Never Trust Extensions: Users can easily rename a malicious .exe file to .jpg. SmartFileKit inspects binary headers (VerifySignature option) to determine the true file format. Always validate signatures in production.
  2. Sanitize Output Names: Do not use the original FileName header directly when writing uploads to disk. Always execute FileName.Sanitize to protect against path traversal attacks.

โšก Performance Optimization

  • Fast Header Scanning: The signature engine scans only the first 4096 bytes of a file, keeping execution times under milliseconds even for multi-gigabyte uploads.
  • Rewindable Streams: If the input Stream supports seeking, its pointer is reset to the starting position when detection concludes. This ensures consecutive writes or downstream handlers receive the stream intact.

๐Ÿ“„ License

This project is licensed under the MIT License.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

    • No dependencies.

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
1.0.3 38 6/19/2026
1.0.2 40 6/19/2026
1.0.1 42 6/19/2026
1.0.0 41 6/19/2026