FileSignatures

repository·master·Indexed 43 days ago

https://github.com/neilharvey/filesignatures

A lightweight C# library for detecting file types using header signatures (magic numbers) instead of file extensions. It provides the FileFormatInspector class to determine file formats from streams and supports custom format extensions and dependency injection for ASP.NET Core.

Tokens
3.4K
Snippets
9
Records
10
Agent score
54%

What's inside FileSignatures

  1. Check for specific file types using the type hierarchy

    master

    File formats are organized into a type hierarchy. You can check for a specific format or use a base type to match multiple related formats using C# pattern matching.

    • Use a specific class (e.g., Pdf) to match exactly one format.
    • Use a base class (e.g., OfficeOpenXml or Image) to match a group of related formats.
    var format = inspector.DetermineFileFormat(stream);
    
    if(format is Pdf) {
      // Just matches Pdf
    }
    
    if(format is OfficeOpenXml) {
      // Matches Word, Excel, Powerpoint
    }
    
    if(format is Image) {
      // Matches any image format
    }
  2. Register FileFormatInspector with Dependency Injection

    master

    You can register IFileFormatInspector in your DI container using two different approaches:

    1. Register all default formats

    Use the empty constructor to include all formats defined in the FileSignatures assembly.

    2. Register a filtered subset of formats

    Use FileFormatLocator.GetFormats() to scan for specific types (e.g., only Image types) and pass that collection to the FileFormatInspector constructor.

    // Option 1: Register all default formats
    services.AddSingleton<IFileFormatInspector>(new FileFormatInspector());
    
    // Option 2: Register only specific types (e.g., Images)
    var recognised = FileFormatLocator.GetFormats().OfType<Image>();
    var inspector = new FileFormatInspector(recognised);
    services.AddSingleton<IFileFormatInspector>(inspector);
  3. Register FileFormatInspector with Dependency Injection in ASP.NET Core

    master

    To use FileFormatInspector in an ASP.NET Core application, you should register a concrete instance in your Startup or Program class. You can filter the available formats using FileFormatLocator.GetFormats() to create an inspector that only recognizes specific types (e.g., Image).

    Register the inspector as a singleton using IFileFormatInspector so it can be injected into your controllers.

    var recognised = FileFormatLocator.GetFormats().OfType<Image>();
    var inspector = new FileFormatInspector(recognised);
    services.AddSingleton<IFileFormatInspector>(inspector);
  4. Add custom file formats

    master

    To extend the library with new formats:

    1. Create a class that inherits from FileFormat.
    2. Use FileFormatLocator.GetFormats(assembly) to load your custom formats from an assembly.
    3. Pass the resulting collection to the FileFormatInspector constructor.

    You can also use FileFormatLocator.GetFormats(assembly, true) to load both your custom formats and the default library formats.

    var assembly = typeof(CustomFileFormat).GetTypeInfo().Assembly;
    
    // Just the formats defined in the assembly containing CustomFileFormat
    var customFormats = FileFormatLocator.GetFormats(assembly);
    
    // Formats defined in the assembly and all the defaults
    var allFormats = FileFormatLocator.GetFormats(assembly, true);
    
    // Pass to inspector
    var inspector = new FileFormatInspector(allFormats);
  5. Run the Console Application example

    master

    The ConsoleApplication example allows you to examine a file's format from the command line. It identifies the file's media type, signature, and extension if the format is recognized.

    To run the example, navigate to the ConsoleApplication directory in your terminal and use the dotnet run command followed by the path to the file you wish to inspect.

    dotnet run /path/to/file
  6. Understand Console Application output

    master

    When the Console Application successfully identifies a file, it returns the following information:

    • Media Type: The MIME type of the file (e.g., image/jpeg).
    • Signature: The hexadecimal signature of the file.
    • Extension: The standard file extension associated with that signature.

    Example output for a JPEG file:

    Media Type : image/jpeg
    Signature  : FF-D8-FF-E0
    Extension  : jpg
  7. Verify uploaded file formats using IFileFormatInspector

    master

    Once IFileFormatInspector is injected into your controller, you can use the DetermineFileFormat method to inspect the actual content of an uploaded file. This is more secure than relying on IFormFile.FileName or IFormFile.ContentType, as it examines the file stream directly.

    1. Open a stream from the IFormFile.
    2. Call DetermineFileFormat(stream).
    3. Check the resulting FileFormat against your expected type (e.g., is Image).
    [HttpPost]
    public IActionResult Index(IFormFile file)
    {
        FileFormat format;
    
        using(var stream = file.OpenReadStream())
        {
            format = fileFormatInspector.DetermineFileFormat(stream);
        }
    
        var model = new UploadResultModel()
        {
            Accepted = format is Image,
            MediaType = format?.MediaType,
            FileName = Path.GetFileName(file.FileName)
        };
    
        return RedirectToAction(nameof(Index), model);
    }
  8. Use FileFormatInspector to determine file types

    master

    To detect a file's format, instantiate FileFormatInspector and call DetermineFileFormat(stream). The method returns a FileFormat instance containing the signature and media type, or null if no match is found.

    var inspector = new FileFormatInspector();
    var format = inspector.DetermineFileFormat(stream);
  9. Reference: Built-in file formats

    master

    The following formats are included by default in the library:

    | Name                       | Media-Type                                                                | Extension |
    |----------------------------|---------------------------------------------------------------------------|-----------|
    | 3GPP                       | video/3gpp                                                                | .3gp      |
    | Bitmap                     | image/bmp                                                                 | .bmp      |
    | Excel                      | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet         | .xlsx     |
    | Excel 97-2003              | application/vnd.ms-excel                                                  | .xls      |
    | Exe (Windows)              | application/octet-stream                                                  | .exe      |
    | GIF                        | image/gif                                                                 | .gif      |
    | JPEG                       | image/jpeg                                                                | .jpg      |
    | MP4                        | video/mp4                                                                | .mp4      |
    | Open Document Presentation | application/vnd.oasis.opendocument.presentationn                          | .odp      |
    | Open Document Spreadhseet  | application/vnd.oasis.opendocument.spreadsheet                            | .ods      |
    | Open Document Text         | application/vnd.oasis.opendocument.text                                   | .odt      |
    | Outlook Message            | application/vnd.ms-outlook                                                | .msg      |
    | PDF                        | application/pdf                                                           | .pdf      |
    | PNG                        | image/png                                                                 | .png      |
    | PowerPoint                 | application/vnd.openxmlformats-officedocument.presentationml.presentation | .pptx     |
    | Powerpoint 97-2003         | application/vnd.ms-powerpoint                                             | .ppt      |
    | QuickTime                  | video/quicktime                                                          | .mov      |
    | Rich Text Format           | application/rtf                                                           | .rtf      |
    | TIFF                       | image/tiff                                                                | .tif      |
    | Visio                      | application/vnd.visio                                                     | .vsdx     |
    | Visio 97-2003              | application/vnd.visio                                                     | .vsd      |
    | Webp                       | image/webp                                                                | .webp     |
    | Word                       | application/vnd.openxmlformats-officedocument.wordprocessingml.document   | .docx     |
    | Word template              | application/vnd.openxmlformats-officedocument.wordprocessingml.template    | .dotx     |
    | Word 97-2003               | application/msword                                                        | .doc      |
    | Xps                        | application/vnd.ms-xpsdocument                                             | .xps      |
    | Zip                        | application/zip                                                           | .zip      |