SaMirzaei.DevTools.Base64 0.1.0-alpha.2

This is a prerelease version of SaMirzaei.DevTools.Base64.
dotnet add package SaMirzaei.DevTools.Base64 --version 0.1.0-alpha.2
                    
NuGet\Install-Package SaMirzaei.DevTools.Base64 -Version 0.1.0-alpha.2
                    
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="SaMirzaei.DevTools.Base64" Version="0.1.0-alpha.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="SaMirzaei.DevTools.Base64" Version="0.1.0-alpha.2" />
                    
Directory.Packages.props
<PackageReference Include="SaMirzaei.DevTools.Base64" />
                    
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 SaMirzaei.DevTools.Base64 --version 0.1.0-alpha.2
                    
#r "nuget: SaMirzaei.DevTools.Base64, 0.1.0-alpha.2"
                    
#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 SaMirzaei.DevTools.Base64@0.1.0-alpha.2
                    
#: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=SaMirzaei.DevTools.Base64&version=0.1.0-alpha.2&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=SaMirzaei.DevTools.Base64&version=0.1.0-alpha.2&prerelease
                    
Install as a Cake Tool

Tools.Base64

A small, dependency-light .NET library for encoding, decoding, and validating Base64 data with an extensible MIME type detection system built on the Strategy pattern.

License: MIT .NET Standard

Features

  • Encode plain text as Base64.
  • Decode Base64 back into UTF-8 text, or preserve it for binary/file-oriented workflows.
  • Validate Base64 input and get structured metadata:
    • Valid/invalid state
    • Decoded size in bytes
    • Heuristic MIME type detection for common file signatures
  • Extensible MIME detection via the Strategy pattern (IMimeTypeDetector).
  • Whitespace-tolerant decoding and validation: spaces and line breaks are ignored.
  • File-aware requests and responses with optional filename, MIME type, and file size metadata.
  • No heavy dependencies — built on the .NET base class library.

Architecture

MIME type detection uses the Strategy pattern, allowing consumers to add custom detectors without modifying existing code.

classDiagram
    class IMimeTypeDetector {
        <<interface>>
        +int Order
        +string Detect(string base64String)
    }

    class DefaultMimeTypeDetector {
        +int Order = 0
        +string Detect(string base64String)
    }

    class RiffMimeTypeDetector {
        +int Order = 10
        +string Detect(string base64String)
    }

    class Base64Service {
        -IEnumerable~IMimeTypeDetector~ _detectors
        +Encode(Base64EncodeRequest) Base64Response
        +Decode(Base64DecodeRequest) Base64Response
        +Validate(Base64ValidateRequest) Base64ValidateResponse
    }

    Base64Service --> IMimeTypeDetector : iterates ordered detectors
    DefaultMimeTypeDetector ..|> IMimeTypeDetector
    RiffMimeTypeDetector ..|> IMimeTypeDetector

Detection flow:

flowchart LR
    A[Base64 input] --> B{Detector Order 0}
    B -->|match| C[Return MIME type]
    B -->|no match| D{Detector Order 10}
    D -->|match| C
    D -->|no match| E{Next detector...}
    E -->|no match| F["application/octet-stream"]

Detectors are evaluated in ascending Order. The first non-empty result wins.

Installation

Add a project reference to the library:

dotnet add reference ../Tools.Base64/Tools.Base64.csproj

Or include it in your solution and reference it from your project.

Usage

using Microsoft.Extensions.DependencyInjection;
using Tools.Base64;

var services = new ServiceCollection();
services.AddBase64Tools();

This registers the built-in detectors (DefaultMimeTypeDetector, RiffMimeTypeDetector) and Base64Service.

Encoding text

using Tools.Base64.Abstractions;
using Tools.Base64.Models;

// Resolve from DI
IBase64Service service = provider.GetRequiredService<IBase64Service>();

var response = service.Encode(new Base64EncodeRequest
{
    Input = "Hello, Base64!"
});

if (response.Success)
    Console.WriteLine(response.Output);

Decoding Base64

var response = service.Decode(new Base64DecodeRequest
{
    Input = "SGVsbG8sIEJhc2U2NCE=",
    OutputAsFile = false
});

if (response.Success && response.IsTextOutput)
    Console.WriteLine(response.Output);
else if (response.Success)
    Console.WriteLine($"Binary content detected: {response.MimeType} ({response.FileSize} bytes)");

Validating Base64

var validation = service.Validate(new Base64ValidateRequest
{
    Input = "SGVsbG8sIEJhc2U2NCE="
});

if (validation.IsValid)
{
    Console.WriteLine($"Decoded size: {validation.DecodedSize} bytes");
    Console.WriteLine($"Estimated MIME type: {validation.EstimatedMimeType}");
}

Adding a custom MIME type detector

Implement IMimeTypeDetector and register it:

using Tools.Base64.Abstractions;

public class FontMimeTypeDetector : IMimeTypeDetector
{
    public int Order => 5; // Runs between default (0) and RIFF (10)

    public string Detect(string base64String)
    {
        if (string.IsNullOrEmpty(base64String) || base64String.Length < 8)
            return string.Empty;

        var prefix = base64String.Substring(0, Math.Min(12, base64String.Length));

        if (prefix.StartsWith("d09GRgAB"))
            return "font/woff2";

        return string.Empty; // Not recognized — pass to next detector
    }
}

Register alongside the built-in detectors:

services.AddBase64Tools();
services.AddSingleton<IMimeTypeDetector, FontMimeTypeDetector>();

Convention: Return string.Empty when your detector does not recognize the input. The service treats any non-empty result as a match and stops the chain.

API

IMimeTypeDetector

Member Description
int Order { get; } Execution priority. Lower values run first.
string Detect(string base64String) Returns the detected MIME type, or string.Empty if unrecognized.

IBase64Service

Method Description
Base64Response Encode(Base64EncodeRequest request) Encodes plain text to Base64, or validates and returns file-oriented Base64 input.
Base64Response Decode(Base64DecodeRequest request) Decodes Base64 and returns either UTF-8 text or binary/file metadata.
Base64ValidateResponse Validate(Base64ValidateRequest request) Validates Base64 input and returns decoded-size and MIME-type hints.

Request model — Base64EncodeRequest

Property Type Default Notes
Input string "" The text to encode, or Base64 file content when IsFile is true.
IsFile bool false When true, the service treats Input as Base64 file data and validates it instead of re-encoding text.
FileName string? null Optional original filename to carry through the response.
MimeType string? null Optional MIME type to carry through the response.

Request model — Base64DecodeRequest

Property Type Default Notes
Input string "" The Base64 string to decode. Whitespace and newlines are ignored.
OutputAsFile bool false When true, returns file-oriented output metadata instead of attempting UTF-8 text output.

Response model — Base64Response

Property Type Notes
Success bool true when the operation completed successfully.
Output string? Encoded Base64, decoded text, or preserved Base64 depending on the operation.
Error string? Error message when the operation fails, or a binary-content hint during decode.
FileName string? Optional filename metadata.
MimeType string? Provided or detected MIME type for file/binary content.
FileSize int? Estimated or decoded file size in bytes when applicable.
IsTextOutput bool true when Output contains decoded text.

Request model — Base64ValidateRequest

Property Type Default Notes
Input string "" The Base64 string to validate.

Validate response — Base64ValidateResponse

Property Type Notes
IsValid bool true when the input is valid Base64.
Error string? Error message when validation fails.
DecodedSize int? The decoded payload size in bytes.
EstimatedMimeType string? Heuristic MIME type inferred from registered detectors.

Built-in MIME type detectors

Detector Order Recognizes
DefaultMimeTypeDetector 0 PNG, JPEG, GIF, WebP, SVG, TIFF, BMP, PDF, ZIP, Office/OpenXML, MS Office, MP3, OGG, MP4, WAV, GZip, RAR
RiffMimeTypeDetector 10 RIFF-based formats (WebP, WAV) via header byte inspection

If no detector matches, the fallback MIME type is application/octet-stream.

Target framework

  • netstandard2.1 — usable from .NET Core 3.x, .NET 5+, and Xamarin/Mono.

Testing

Run the dedicated test project:

dotnet test tests/Tools.Base64.Tests/Tools.Base64.Tests.csproj

License

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 netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen 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.

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
0.1.0-alpha.2 74 7/14/2026
0.1.0-alpha.1 92 6/17/2026