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
- MP3
- EMF
- TIFF
- ICO
- WMF
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
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);
}
}
Thanks to JetBrains for supporting open source projects by providing JetBrains Rider IDE for free.