Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 views
in Technique[技术] by (71.8m points)

iis - ASP.NET/IIS6: How to search the server's mime map?

i want to find the mime-type for a given file extension on an IIS ASP.NET web-server from the code-behind file.

i want to search the same list that the server itself uses when serving up a file. This means that any mime types a web-server administrator has added to the Mime Map will be included.

i could blindly use

HKEY_CLASSES_ROOTMIMEDatabaseContent Type

but that isn't documented as being the same list IIS uses, nor is it documented where the Mime Map is stored.

i could blindly call FindMimeFromData, but that isn't documented as being the same list IIS uses, nor can i guarantee that the IIS Mime Map will also be returned from that call.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...