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

后端 未结 5 2000
别跟我提以往
别跟我提以往 2020-12-28 22:49

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 m

5条回答
  •  情话喂你
    2020-12-28 23:02

    You can search for a site by inspecting the ServerComment property belonging to children of the metabase path IIS://Localhost/W3SVC that have a SchemaClassName of IIsWebServer.

    The following code demonstrates two approaches:

    string siteToFind = "Default Web Site";
    
    // The Linq way
    using (DirectoryEntry w3svc1 = new DirectoryEntry("IIS://Localhost/W3SVC"))
    {
        IEnumerable children = 
              w3svc1.Children.Cast();
    
        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 ServerComment property has been used (IIS MMC forces its used) and is unique.

提交回复
热议问题