This code snippet enumerates every Website on the local IIS server using C# and ADSI.

// ------------------------
// This requires the following using statement
using System.DirectoryServices;
// ------------------------

// Connect to the w3svc object
DirectoryEntry w3svc = new DirectoryEntry("IIS://localhost/w3svc");

// Loop through all children
foreach (DirectoryEntry child in w3svc.Children)
{
  // Grab the Website Object (IIsWebServer)
  if (child .SchemaClassName == "IIsWebServer")
  {
    // Write out the name of the Website (ServerComment) and the Identifier (Name)
    Console.WriteLine(child .Properties["ServerComment"].Value + " with ID : " + child .Name);
  }
}

// Pause the output (so you can view it's result)
Console.ReadLine();
Tagged with: