Search code examples
c#content-typefile-extension

Get extension from Content-Type


This is a very straight forward question.

I have a Content-Type stored in the form of a string.

Ideally I'd like to infer an extension from that Content-Type without having to have a giant nasty switch case.

Is there a built in construct to achieve this?

Btw, I found this question but that goes the opposite direction from extension to content-type.


Solution

  • You'll want a Dictionary. This will allow you to look up an extension for a given content type:

    Dictionary<string, string> extensionLookup = new Dictionary<string, string>()
    {
        {"ContentType1", ".ext1"},
        {"ContentType2", ".ext2"},
    };
    

    You can populate the dictionary based on a database table, a file, etc. rather than hard coding the values.

    Once you have the Dictionary it's as simple as:

    string extension = extensionLookup[someContentType];