Here is another similar implementation, but doesn't require adding the COM reference - it retrieves the properties through reflection instead and stores them in a NameValueCollection for easy lookup:
using System.Collections.Specialized; //NameValueCollection
using System.DirectoryServices; //DirectoryEntry, PropertyValueCollection
using System.Reflection; //BindingFlags
NameValueCollection map = new NameValueCollection();
using (DirectoryEntry entry = new DirectoryEntry("IIS://localhost/MimeMap"))
{
PropertyValueCollection properties = entry.Properties["MimeMap"];
Type t = properties[0].GetType();
foreach (object property in properties)
{
BindingFlags f = BindingFlags.GetProperty;
string ext = t.InvokeMember("Extension", f, null, property, null) as String;
string mime = t.InvokeMember("MimeType", f, null, property, null) as String;
map.Add(ext, mime);
}
}
You can very easily cache that lookup table, and then reference it later:
Response.ContentType = map[ext] ?? "binary/octet-stream";
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…