Search code examples
c#.netiisinstallationwmi

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


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.:

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")?


Solution

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