Get MIME type from filename extension

user34537 picture user34537 · Jun 23, 2009 · Viewed 315.7k times · Source

How can I get the MIME type from a file extension?

Answer

Shimmy Weitzhandler picture Shimmy Weitzhandler · Jan 1, 2013

For ASP.NET or other

The options were changed a bit in ASP.NET Core, here they are (credits):

  • new FileExtensionContentTypeProvider().TryGetContentType(fileName, out contentType); (vNext only)
    • Never tested, but looks like you can officially expand the mime types list via the exposed Mappings property.
  • Use the MimeTypes NuGet package
  • Copy the MimeMappings file from the reference source of the .NET Framework

For .NET Framework >= 4.5:

Use the System.Web.MimeMapping.GetMimeMapping method, that is part of the BCL in .NET Framework 4.5:

string mimeType = MimeMapping.GetMimeMapping(fileName);

If you need to add custom mappings you probably can use reflection to add mappings to the BCL MimeMapping class, it uses a custom dictionary that exposes this method, so you should invoke the following to add mappings (never tested tho, but should prob. work).

Anyway, when using reflection to add MIME types, be aware that since you're accessing a private field, its name might change or even be totally removed, so you should be extra cautious and add double checks and provide fail safe action for every step.

MimeMapping._mappingDictionary.AddMapping(string fileExtension, string mimeType)