MimeMaster 1.0.0-preview.1

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

๐Ÿง™โ€โ™‚๏ธ MimeMaster

License: MIT Build Status Tests NuGet Downloads Coverage Status

MimeMaster is a fast, accurate .NET library for detecting and validating file types based on file signatures (magic numbers). It provides reliable file type detection regardless of file extensions by examining file headers and trailers.

โœจ Features

  • ๐Ÿ” Accurate MIME type detection based on file signatures
  • โœ… File validation against allowed MIME types and size constraints
  • ๐Ÿ“ฆ Support for common file formats: PDF, Office documents, images, and more
  • ๐Ÿงฉ Extensible design for adding custom file types
  • ๐Ÿ”„ Integration with .NET dependency injection

๐Ÿ“ฆ Installation

Package Manager Console

Install-Package MimeMaster

.NET CLI

dotnet add package MimeMaster

๐Ÿš€ Quick Start

Basic Usage

// Create services manually
var logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger<FileTypeService>();
var fileTypeService = new FileTypeService(logger);

// Detect MIME type
string filePath = "path/to/your/file.pdf";
byte[] fileData = File.ReadAllBytes(filePath);
var fileType = fileTypeService.GetMimeType(filePath, fileData);

Console.WriteLine($"MIME type: {fileType.Mime}");
Console.WriteLine($"Extension: {fileType.Extension}");

With Dependency Injection

// In Startup.ConfigureServices or Program.cs
services.AddMimeMaster();

// In your controller or service
public class MyService
{
    private readonly IFileTypeService _fileTypeService;
    private readonly IValidationService _validationService;
    
    public MyService(IFileTypeService fileTypeService, IValidationService validationService)
    {
        _fileTypeService = fileTypeService;
        _validationService = validationService;
    }
    
    public void ProcessFile(string filePath)
    {
        byte[] fileData = File.ReadAllBytes(filePath);
        
        // Detect MIME type
        var fileType = fileTypeService.GetMimeType(filePath, fileData);
        
        // Validate file
        string allowedMimeTypes = "application/pdf,image/jpeg,image/png";
        long maxFileSize = 5 * 1024 * 1024; // 5MB
        
        var validationResult = _validationService.Validate(
            filePath, 
            fileData, 
            allowedMimeTypes, 
            maxFileSize);
            
        if (validationResult.HasFailed)
        {
            foreach (var invalidFile in validationResult.InvalidFiles)
            {
                Console.WriteLine($"Validation failed: {invalidFile.Errors}");
            }
        }
    }
}

๐Ÿ“‹ Supported File Types

MimeMaster currently supports the following file types:

  • ๐Ÿ“„ PDF (.pdf)
  • ๐Ÿ“ Word Documents (.doc, .docx)
  • ๐Ÿ“Š Excel Spreadsheets (.xls, .xlsx)
  • ๐Ÿ“Š PowerPoint Presentations (.ppt, .pptx)
  • ๐Ÿ–ผ๏ธ Images (.jpg, .jpeg, .png, .bmp, .gif)
  • ๐ŸŽฌ Video (.mp4, .flv)
  • ๐Ÿ“„ Text (.txt, .rtf)

๐Ÿ” File Signatures

File signatures, also known as "magic numbers" or "magic bytes," are specific patterns at the beginning (headers) or end (trailers) of a file that identify its type regardless of file extension. MimeMaster uses these signatures to accurately identify file types.

The implementation is inspired by file signature tables and format specifications.

Common File Signatures

Format     Hex Signature                ASCII        Trailer                        Description
-------    -------------                -----        -------                        -----------
DOC/XLS    D0 CF 11 E0 A1 B1 1A E1     รร.ร ยกยฑ.รก     -                              MS Office OLE Compound File
PDF        25 50 44 46 2D               %PDF-        0A 25 25 45 4F 46 (.%%EOF)     PDF Document
                                                     0A 25 25 45 4F 46 0A (.%%EOF.)
                                                     0D 0A 25 25 45 4F 46 0D 0A     
                                                     0D 25 25 45 4F 46 0D (.%%EOF.)
PNG        89 50 4E 47 0D 0A 1A 0A      โ€ฐPNG....     49 45 4E 44 AE 42 60 82        PNG Image
                                                     (IENDยฎB`โ€š...)
DOCX/PPTX  50 4B 03 04 14 00 06 00      PK......     50 4B 05 06 (PK..) + 18 bytes  Office Open XML (OOXML) Document
XLSX                                                 at the end of the file
JPG        FF D8                         รฟร˜          FF D9                          JPEG Image
ZIP        50 4B 03 04                   PK..        -                              ZIP Archive
PST        21 42 44 4E                   !BDN        -                              MS Outlook Personal Folder

MS Office Subheaders

Office binary formats (DOC, XLS, PPT) have specific subheaders at byte offset 512:

Format   Offset        Hex Signature                Description
------   ------        -------------                -----------
DOC      512           EC A5 C1 00                  Word document subheader
XLS      512           FD FF FF FF nn 00            Excel spreadsheet subheader
         or 512        FD FF FF FF nn 02            
         or 512        09 08 10 00 00 06 05 00      
PPT      512           A0 46 1D F0                  PowerPoint presentation subheader
         or 512        00 6E 1E F0
         or 512        0F 00 E8 03
         or 512        FD FF FF FF nn nn 00 00

Microsoft Office OOXML Formats

For Microsoft Office Open XML formats (DOCX, PPTX, XLSX), there is a specific detection pattern:

  • Header signature: 50 4B 03 04 14 00 06 00 ("PK......")
  • Trailer signature: Look for 50 4B 05 06 ("PK..") followed by 18 additional bytes at the end of the file

Unlike the older Office formats (DOC, PPT, XLS), there is no subheader for OOXML files. OOXML files are essentially ZIP files, so you can rename them with a .ZIP extension and then extract them to examine their contents. Inside, you'll find the [Content_Types].xml file that describes the content types, along with specific XML files:

  • DOCX: Look for word/document.xml
  • XLSX: Look for xl/workbook.xml
  • PPTX: Look for ppt/presentation.xml

When examining the [Content_Types].xml file, look for the <Override PartName= tag, where you will find word, ppt, or xl, respectively.

The library includes signatures for various file formats and can be extended to support additional formats as needed.

๐Ÿ“š API Reference

IFileTypeService

public interface IFileTypeService
{
    FileType GetMimeType(string fileName, byte[] fileData);
}

IValidationService

public interface IValidationService
{
    ValidationResult Validate(
        string fileName, 
        byte[] fileData, 
        string allowedMimeTypes, 
        long maxFileSize, 
        long minFileSize = 0);
}

ValidationErrors

[Flags]
public enum ValidationErrors
{
    None = 0,
    FileTypeNotAllowed = 1 << 0,
    FileTooLarge = 1 << 1,
    FileTooSmall = 1 << 2,
    FileTypeUnknown = 1 << 3
}

๐Ÿ“Š Performance

MimeMaster is designed for high-performance applications:

  • โšก Fast detection: Optimized signature matching algorithms
  • ๐Ÿง  Low memory overhead: Minimal allocations during detection
  • ๐Ÿ”„ Thread-safe: Safe for concurrent use

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Commit your changes: git commit -m 'Add amazing feature'
  4. Push to the branch: git push origin feature/amazing-feature
  5. Open a Pull Request

๐Ÿ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • File signatures information sourced from various format specifications and references
  • Inspired by other open-source MIME type detection libraries

<p align="center">Made with โค๏ธ for the .NET community</p>

MimeMaster

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  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. 
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
1.0.0-preview.1 215 5/15/2025