In C#, there are several ways to determine the MIME type of a file. Here are the most common approaches:
1. Use Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider (Recommended in ASP.NET Core)
using Microsoft.AspNetCore.StaticFiles;
var provider = new FileExtensionContentTypeProvider();
if (!provider.TryGetContentType("example.pdf", out string contentType))
{
contentType = "application/octet-stream"; // default fallback
}
Console.WriteLine(contentType); // Outputs: application/pdf
using MimeDetective;
var inspector = new ContentInspectorBuilder()
.AddDefaults()
.Build();
var fileInfo = new FileInfo("example.png");
var result = inspector.Inspect(fileInfo);
Console.WriteLine(result?.MimeType); // Outputs: image/png
Best for file content validation (e.g., to detect forged extensions)
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In C#, there are several ways to determine the MIME type of a file. Here are the most common approaches:
1. Use
Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider(Recommended in ASP.NET Core)Microsoft.AspNetCore.StaticFilesNuGet package2. Use Windows Registry via
System.Web.MimeMapping(Only on Windows / ASP.NET)3. Use
Registry(Windows-only)Platform-specific — Windows only.
4. Use File Content (Magic Numbers) with
MimeDetective(Advanced)If you want to inspect the actual file content (not just the extension), use third-party libraries like:
Example using MimeDetective:
Best for file content validation (e.g., to detect forged extensions)
Summary
FileExtensionContentTypeProviderSystem.Web.MimeMappingRead More -