Monday
Apr042011

Listing all mime types without using OLE and IIS in .NET

Download full solution

If you're offering uploading on a web application, or providing a file proxy of some sort, at some point the list of files you offer will exceed a simple switch statement.

In order for the file to be recognised correctly by the browser that's downloading the file you need to pass the correct headers back. You can do this the long, more complete wawy by querying the IIS mimetype metabase (which requires COM interop with IIS6).

Or you can cheat and simply query an XML file list of mimetypes. The application below does this, based on a list from webmaster-toolkit.com.

The full download includes the XML serialized file.

Usage

class Program
{
    static void Main(string[] args)
    {
        var list = MimeType.Load();
        MimeType mimetype = list.FirstOrDefault(m => m.Extension == "jpg");
    }
}

MimeType class

public class MimeType
{
    public string Extension { get; set; }
    public string Value { get; set; }

    public MimeType()
    {
        Extension = "";
        Value = "";
    }

    public MimeType(string extension, string value)
    {
        Extension = extension;
        Value = value;
    }

    public static IEnumerable<MimeType> Load()
    {
        IList<MimeType> mimeTypes = new List<MimeType>();
        try
        {
            using (Stream stream = typeof(MimeType).Assembly.GetManifestResourceStream("MimeTypes.mimetypes.xml"))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(List<MimeType>));
                mimeTypes = (IList<MimeType>) serializer.Deserialize(stream);
            }
        }
        catch (Exception)
        {
            // Re throw if you need
        }

        return mimeTypes;
    }
}

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
« Installing Windows 7 on a USB stick | Main | The new Spruce solution structure »