这是另一个类似的实现,但不需要添加 COM 引用 - 它通过反射检索属性并将它们存储在 NameValueCollection 中以便于查找:
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);
}
}
您可以非常轻松地缓存该查找表,然后稍后引用它:
Response.ContentType = map[ext] ?? "binary/octet-stream";