Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 836
Grzenio Avatar asked Mar 19 '09 16:03

Grzenio


People also ask

How do I find the site ID?

Go to Administration (click on the gear icon in the top right of the screen). Click on the Measurables(or Websites) > Manage page. You will find a list of all websites on this page. The website ID is on the left of the table listing all websites directly below the website name.


1 Answers

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;
}
like image 129
Glennular Avatar answered Nov 01 '22 03:11

Glennular