如何在 C# 中查找 IIS 站点 ID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/662879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 12:22:44  来源:igfitidea点击:

How can I look up IIS site id in C#?

c#.netiisinstallerwmi

提问by Grzenio

I am writing an installer class for my web service. In many cases when I use WMI (e.g. when creating virtual directories) I have to know the siteId to provide the correct metabasePath to the site, e.g.:

我正在为我的 Web 服务编写一个安装程序类。在许多情况下,当我使用 WMI 时(例如在创建虚拟目录时),我必须知道 siteId 才能为站点提供正确的元数据库路径,例如:

metabasePath is of the form "IIS://<servername>/<service>/<siteID>/Root[/<vdir>]"
for example "IIS://localhost/W3SVC/1/Root" 

How can I look it up programmatically in C#, based on the name of the site (e.g. for "Default Web Site")?

如何根据站点名称(例如“默认网站”)在 C# 中以编程方式查找它?

采纳答案by Glennular

Here is how to get it by name. You can modify as needed.

这是按名称获取它的方法。您可以根据需要进行修改。

public int GetWebSiteId(string serverName, string websiteName)
{
  int result = -1;

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

回答by Sébastien Nussbaumer

Maybe not the best way, but here is a way :

也许不是最好的方法,但这里有一个方法:

  1. loop through all the sites under "IIS://servername/service"
  2. for each of the sites check if the name is "Default Web Site" in your case
  3. if true then you have your site id
  1. 遍历“IIS://servername/service”下的所有站点
  2. 对于每个站点,在您的情况下检查名称是否为“默认网站”
  3. 如果为真,那么你有你的网站 ID

Example :

例子 :

Dim oSite As IADsContainer
Dim oService As IADsContainer
Set oService = GetObject("IIS://localhost/W3SVC")
For Each oSite In oService
    If IsNumeric(oSite.Name) Then
        If oSite.ServerComment = "Default Web Site" Then
            Debug.Print "Your id = " & oSite.Name
        End If
    End If
Next

回答by Kev

You can search for a site by inspecting the ServerCommentproperty belonging to children of the metabase path IIS://Localhost/W3SVCthat have a SchemaClassNameof IIsWebServer.

您可以通过检查搜索的网站ServerComment属于数据库路径的子女财产IIS://Localhost/W3SVC有一个SchemaClassNameIIsWebServer

The following code demonstrates two approaches:

以下代码演示了两种方法:

string siteToFind = "Default Web Site";

// The Linq way
using (DirectoryEntry w3svc1 = new DirectoryEntry("IIS://Localhost/W3SVC"))
{
    IEnumerable<DirectoryEntry> children = 
          w3svc1.Children.Cast<DirectoryEntry>();

    var sites = 
        (from de in children
         where
          de.SchemaClassName == "IIsWebServer" &&
          de.Properties["ServerComment"].Value.ToString() == siteToFind
         select de).ToList();
    if(sites.Count() > 0)
    {
        // Found matches...assuming ServerComment is unique:
        Console.WriteLine(sites[0].Name);
    }
}

// The old way
using (DirectoryEntry w3svc2 = new DirectoryEntry("IIS://Localhost/W3SVC"))
{

    foreach (DirectoryEntry de in w3svc2.Children)
    {
        if (de.SchemaClassName == "IIsWebServer" && 
            de.Properties["ServerComment"].Value.ToString() == siteToFind)
        {
            // Found match
            Console.WriteLine(de.Name);
        }
    }
}

This assumes that the ServerCommentproperty has been used (IIS MMC forces its used) and is unique.

这假定该ServerComment属性已被使用(IIS MMC 强制其使用)并且是唯一的。

回答by CodeMonkeyKing

private static string FindWebSiteByName(string serverName, string webSiteName)
{
    DirectoryEntry w3svc = new DirectoryEntry("IIS://" + serverName + "/W3SVC");
    foreach (DirectoryEntry site in w3svc.Children)
    {
        if (site.SchemaClassName == "IIsWebServer"
            && site.Properties["ServerComment"] != null
            && site.Properties["ServerComment"].Value != null
            && string.Equals(webSiteName, site.Properties["ServerComment"].Value.ToString(), StringComparison.OrdinalIgnoreCase))
        {
            return site.Name;
        }
    }

    return null;
}

回答by CodeMonkeyKing

public static ManagementObject GetWebServerSettingsByServerComment(string serverComment)
        {
            ManagementObject returnValue = null;

            ManagementScope iisScope = new ManagementScope(@"\localhost\root\MicrosoftIISv2", new ConnectionOptions());
            iisScope.Connect();
            if (iisScope.IsConnected)
            {
                ObjectQuery settingQuery = new ObjectQuery(String.Format(
                    "Select * from IIsWebServerSetting where ServerComment = '{0}'", serverComment));

                ManagementObjectSearcher searcher = new ManagementObjectSearcher(iisScope, settingQuery);
                ManagementObjectCollection results = searcher.Get();

                if (results.Count > 0)
                {
                    foreach (ManagementObject manObj in results)
                    {
                        returnValue = manObj;

                        if (returnValue != null)
                        {
                            break;
                        }
                    }
                }
            }

            return returnValue;
        }