获取IIS-7及更高版本的网站ID

通过将ID作为参数传递,我能够以编程方式(C#)获取IIS-7(C:\ Windows \ System32 \ inetsrv \ config \ applicationHost.config)中托管的任何网站的物理路径。 但是通过代码找到Id失败的iis7。 错误消息是

COMException(0x80005000):未知错误(0x80005000)

即使在添加Microsoft.Web.Administration程序集( http://cstruter.com/blog/306 )后仍无法解决。

作为参考,这是我用来获取ID的代码:

public static int GetWebSiteId(string serverName, string websiteName) { int result = 2; DirectoryEntry w3svc = new DirectoryEntry( string.Format("IIS://{0}/w3svc", serverName)); foreach (DirectoryEntry site in w3svc.Children) { if (site.Properties["ServerComment"] != null) { if (site.Properties["ServerComment"].Value != null) { if (string.Compare(site.Properties["ServerComment"].Value.ToString(), websiteName, false) == 0) { result = int.Parse(site.Name); break; } } } } return result; } 

您是否尝试使用新的ServerManager对象(适用于IIS 7.0及更高版本,通过Microsoft.Web.Administration)?

请尝试使用以下代码段:

 using (ServerManager serverManager = new ServerManager()) { var sites = serverManager.Sites; foreach (Site site in sites) { Console.WriteLine(site.Id); } 

为了获得一个特定网站的ID,LINQ就像一个魅力。