Listing all mime types without using OLE and IIS in .NET
April 04, 2011
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 way 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. Update - that’s now a dead link. This link has a list (thanks Tim).
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; | |
} | |
} |
I'm Chris Small, a software engineer working in London. This is my tech blog. Find out more about me via Github, Stackoverflow, Resume