Skip to content
/ DMime Public

Detects a given file's MIME type based on file content regardless of file extension

License

Notifications You must be signed in to change notification settings

litenova/DMime

Repository files navigation

Dmime

CI/CD NuGet Coverage Status

A fast and efficient library to detect a given file's MIME type based on the file content regardless of file extension.

  • Written in .NET 7
  • No Dependencies
  • No Reflection
  • Easy to Use
  • Supported Types
    • MP4
    • BMP
    • GIF
    • JPEG
    • PNG
    • WEBP
    • PDF
    • MP3
    • EMF
    • TIFF
    • ICO
    • WMF

How to Use

Extension Method

Install the DMime package:

dotnet add package Dmime

Then use the DetectMimeTypeAsync or DetectMimeType extension methods on any Stream type.

    // an unkown file without extension
FileStream stream = File.OpenRead("webp-sample-550w-404h");

var result = await stream.DetectMimeTypeAsync(); // result = image/webp

Dependency

Install the Dmime.Extensions.MicrosoftDependencyInjection package:

dotnet add package Dmime.Extensions.MicrosoftDependencyInjection

Register the dependency into ASP.NET Core DI container:

services.AddMimeDetector();

Then inject the IMimeDetector to your desired class and use the DetectAsync or Detect methods accordingly.

  [ApiController]
  [Route("[controller]")]
  public class UploadController
  {
      private readonly IMimeDetector _mimeDetector;
  
      public UploadController(IMimeDetector mimeDetector)
      {
          _mimeDetector = mimeDetector;
      }
  
      [HttpPost]
      public async Task<IActionResult> SendNotification(IFormFile formFile)
      {
          var streamContent = formFile.OpenReadStream();
                  
          var result = await _mimeDetector.DetectMimeTypeAsync(streamContent);
  
          return Ok(result);
      }
  }

Sponsor

Thanks to JetBrains for supporting open source projects by providing JetBrains Rider IDE for free.

alt text

About

Detects a given file's MIME type based on file content regardless of file extension

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages