Galin Iliev's blog

Software Architecture & Development

Start/Stop IIS Site with C#

Have you ever had you deal with IIS management using C#? I mean IIS6?

for IIS 6 you had to deal with DirectoryEntry class like this (code got from here):


   1:  try
   2:  {
   3:      const string WebServerSchema = "IIsWebServer"; // Case Sensitive
   4:      string ServerName = "localhost";
   5:      DirectoryEntry W3SVC = new DirectoryEntry("IIS://" + ServerName + "/w3svc");
   6:      foreach (DirectoryEntry Site in W3SVC.Children)
   7:      {
   8:          if (Site.SchemaClassName == WebServerSchema)
   9:          {
  10:              Console.WriteLine(Site.Name + " - " + Site.Properties["ServerComment"].Value.ToString());
  11:          }
  12:      }
  13:  }
  14:  // Catch any errors
  15:  catch (Exception e)
  16:  {
  17:      Console.WriteLine("Error: " + e.ToString());
  18:  }


and once you find your site you had to execute DirectoryEntry.Invoke("Start", null) or DirectoryEntry.Invoke("Stop", null)  in order to start/stop the site.

Not very convinient but works :).

Well with IIS7 there are a good news and bad news... The bad news is this code won't work on IIS7 (and Vista).

The good news is that there is new .NET assembly () for managing IIS. It is located in %WinDir%\System32\InetSrv\Microsoft.Web.Administration.dll. It contains some wrapper classes that makes dev life much easier :)

with it the task above become:

   1:  ServerManager iisManager = new ServerManager();
   2:  iisManager.Sites["NewSite"].Stop(); 

Much prettier huh?! :)

for more info about Microsoft.Web.Administration.dll read CarlosAg blog's entry Microsoft.Web.Administration in IIS 7

Loading