如何在C#中查找IIS站点ID?我正在为我的网络服务编写一个安装程序类。在许多情况下,当我使用WMI时(例如,在创建虚拟目录时),我必须知道siteId才能为站点提供正确的metabasePath,例如:metabasePath的形式为“IIS://///Root[/]”例如“IIS://localhost/W3SVC/1/Root”如何根据网站名称(例如“默认网站”)以编程方式在C#中查找?这是通过名称获取它的方法。您可以根据需要修改它。publicintGetWebSiteId(stringserverName,stringwebsiteName){intresult=-1;DirectoryEntryw3svc=newDirectoryEntry(string.Format("IIS://{0}/w3svc",serverName));foreach(w3svc.Children中的DirectoryEntry站点){如果(site.Properties["ServerComment"]!=null){如果(site.Properties["ServerComment"].Value!=null){如果(string.Compare(site.Properties["ServerComment"].Value.ToString(),websiteName,false)==0){result=int.Parse(site.Name);休息;}}}}返回结果;您可以通过使用SchemaClassNameIIsWebServerIIS://Localhost/W3SVC子项的ServerComment属性检查属于配置数据库的路径来搜索站点。以下代码演示了这两种方法:stringsiteToFind="DefaultWebSite";//Linq方式使用(DirectoryEntryw3svc1=newDirectoryEntry("IIS://Localhost/W3SVC")){IEnumerablechildren=w3svc1.Children.Cast();varsites=(fromdeinchildrenwherede.SchemaClassName=="IIsWebServer"&&de.Properties["ServerComment"].Value.ToString()==siteToFindselectde).ToList();if(sites.Count()>0){//找到匹配...假设ServerComment是唯一的:Console.WriteLine(sites[0].Name);}}//旧方法使用(DirectoryEntryw3svc2=newDirectoryEntry("IIS://Localhost/W3SVC")){foreach(DirectoryEntrydeinw3svc2.Children){if(de.SchemaClassName=="IIsWebServer"&&de.Properties["ServerComment"].Value.ToString()==siteToFind){//找到匹配Console.WriteLine(de.Name);}}}这假定已使用ServerComment属性(IISMMC强制执行)并且是唯一的。publicstaticManagementObjectGetWebServerSettingsByServerComment(stringserverComment){ManagementObjectreturnValue=null;ManagementScopeiisScope=newManagementScope(@"\localhostrootMicrosoftIISv2",newConnectionOptions());iisScope.Connect();if(iisScope.IsConnected){ObjectQuerysettingQuery=newObjectQuery(String.Format("Select*fromIIsWebServerSettingwhereServerComment='{0}'",serverComment));ManagementObjectSearcher搜索器=newManagementObjectSearcher(iisScope,settingQuery);ManagementObjectCollection结果=searcher.Get();if(results.Count>0){foreach(ManagementObjectmanObjinresults){returnValue=manObj;如果(返回值!=null){中断;}}}}返回返回值;}privatestaticstringFindWebSiteByName(stringserverName,stringwebSiteName){DirectoryEntryw3svc=newDirectoryEntry("IIS://"+serverName+"/W3SVC");foreach(w3svc.Children中的DirectoryEntry站点){如果(site.SchemaClassName=="IIsWebServer"&&site.Properties["ServerComment"]!=null&&site.Properties["ServerComment"].Value!=null&&string.Equals(webSiteName,site.Properties["ServerComment"].Value.ToString(),StringComparison.OrdinalIgnoreCase)){returnsite.Name;}}返回空值;}也许不是最好的方法,但这是一种方法:遍历每个站点的“IIS://servername/service”下的所有站点,检查您的案例中的名称是否为“默认网站”如果为真,那么您有siteID示例:以上是C#学习教程:如何在C#中查找IIS站点ID?所有分享的内容,如果对你有用,需要了解更多C#学习教程,希望大家多多关注——DimoSiteAsIADsContainerDimoServiceAsIADsContainerSetoService=GetObject("IIS://localhost/W3SVC")ForEachoSiteInoServiceIfIsNumeric(oSite.Name)ThenIfoSite.ServerComment="DefaultWebSite"ThenDebug.Print"Yourid="&oSite.NameEndIfEndIfNext本文采集自网络且不代表立场,如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
