In a previous post, “Use Constants For MIME Types”, we discussed how to avoid specifying strings for MIME types and use built-in constants instead.

The problem with this is that you needed to know the MIME type in advance, making the code a lot more complicated when you didn’t.

You would typically need to write a giant switch statement like so:

var extension = "";
var mimeType = "";
switch (extension)
{
  case ".pdf":
    mimeType = "application/pdf";
    break;
    //
    // Other types here
    //
  default:
    mimeType = "text/plain";
    break;
}

Alternatively, you had to use a third-party Nuget package.

This is now addressed with the new MediaTypeMap class, using the GetMediaType method.

You use it as follows:

var mediaType = MediaTypeMap.GetMediaType(".txt");
Console.WriteLine(mediaType);

This will print the following:

text/plain

The method takes one of the following:

  • The extension (without a period)
  • The extension (with a period)
  • The complete file name

In other words, these yield the same result:

MediaTypeMap.GetMediaType(".txt");
MediaTypeMap.GetMediaType("txt");
MediaTypeMap.GetMediaType("mango.txt");

A few more examples:

// PDF
var mediaType = MediaTypeMap.GetMediaType(".pdf");
Console.WriteLine(mediaType);
// MP4
mediaType = MediaTypeMap.GetMediaType(".mp4");
Console.WriteLine(mediaType);
// Excel
mediaType = MediaTypeMap.GetMediaType(".xlsx");
Console.WriteLine(mediaType);
// Unknown
mediaType = MediaTypeMap.GetMediaType(".dsf");
Console.WriteLine(mediaType);

These will return the following:

mimeResults

Of interest here is that if the file type is unknown, a null will be returned. You can test for this in your code.

TLDR

The MediaTypeMap class in System.Net.Mime.MediaTypeMap can be used to get MIME types from extensions.

Happy hacking!