Restarting an IIS6 app pools using .NET

This week I was writing an admin tool that needed to recycle some IIS6 application pools. I found two ways to do it, one using Window Management Instrumentation (WMI) and the other using the DirectoryEntry class (part of the active directory classes).

Here’s a little code sample for the WMI way:

  1. ManagementScope scope = new ManagementScope(@”\\localhost\root\MicrosoftIISv2");
  2. WqlObjectQuery query =
  3.  new WqlObjectQuery(@”SELECT * FROM IIsApplicationPool  WHERE Name LIKE '% .NET2'");
  4. ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
  5. foreach (ManagementObject appPool in searcher.Get())
  6. {
  7.     appPool.InvokeMethod("Recycle", null);
  8. }

Here’s a code sample for the DirectoryEntry way:

  1. DirectoryEntry appPools =
  2.     new DirectoryEntry("IIS://localHost/w3svc/AppPools", "", "");
  3. foreach (DirectoryEntry child in appPools.Children)
  4. {
  5.     if (child.Name.EndsWith(".NET2"))
  6.     {
  7.         child.Invoke("Recycle", null);
  8.     }
  9. }

There are some more great examples of how to do these types of things on stack overflow.

Posted on 09 Aug 09 by Helen Emerson (last updated on 09 Aug 09).
Filed under .NET