如何以编程方式读取IIS MIME类型?我想在将数据流式传输到客户using WCF时使用它们。
任何提示或API都将不胜感激
答案 0 :(得分:13)
我假设这只是IIS7而你正在使用C#3.0或更高版本:
using Microsoft.Web.Administration;
....
using(ServerManager serverManager = new ServerManager())
{
// If interested in global mimeMap:
var config = serverManager.GetApplicationHostConfiguration();
// Use if interested in just a particular site's mimeMap:
// var config = serverManager.GetWebConfiguration("Default Web Site");
var staticContent = config.GetSection("system.webServer/staticContent");
var mimeMap = staticContent.GetCollection();
// Print all mime types
foreach (var mimeType in mimeMap)
{
Console.WriteLine(String.Format("{0} = {1}", mimeType["fileExtension"],
mimeType["mimeType"]));
}
// Find a mime type based on file extension
var mt = mimeMap.Where(
a => (string) a.Attributes["fileExtension"].Value == ".pdf"
).FirstOrDefault();
if (mt != null)
{
Console.WriteLine("Mime type for .pdf is: " + mt["mimeType"]);
}
}
您需要引用Microsoft.Web.Administration.dll
中的c:\windows\system32\inetsrv
。
您的代码也需要管理员权限才能执行此操作。
答案 1 :(得分:6)
如果使用ASP.Net 4.5或更高版本,您可以使用System.Web.MimeMapping.GetMimeMapping
,如下所示:
void Page_Init()
{
string[] extensions = new string[]
{
".pdf",
".xls",
".xlsx",
".ppt",
".pptx",
".mp3",
".ogg",
".svg",
".pdf",
".png",
};
foreach (string extension in extensions)
{
string mimeType = MimeMapping.GetMimeMapping(extension);
Response.Write(String.Format("{0} => {1}<br />",
extension,
mimeType
));
}
}
结果:
.pdf => application/pdf
.xls => application/vnd.ms-excel
.xlsx => application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.ppt => application/vnd.ms-powerpoint
.pptx => application/vnd.openxmlformats-officedocument.presentationml.presentation
.mp3 => audio/mpeg
.ogg => video/ogg
.svg => image/svg+xml
.pdf => application/pdf
.png => image/png
答案 2 :(得分:2)
注册到系统的Mime类型在注册表中的“HKEY_CLASSES_ROOT \ Mime \ Database \ Content Type”下定义。
您是否在寻找IIS中定义的特定网站的mime类型?
答案 3 :(得分:0)
作为读取注册表或降低config目录安全性的替代方法,HTML Agility Pack
中有一个预先填充的MIME数据库