Home > Development > .NET C#: Recycle current Application Pool programmatically (for IIS 6+)

.NET C#: Recycle current Application Pool programmatically (for IIS 6+)

I’ve been working on how to recycle the current application pool for my ASP .NET application.

There are 3 steps for doing this:

  1. Verify if application is running on IIS that supports application pools (if not, there’s nothing to recycle).
  2. Get application pool name (obtained from the DirectoryServices entry corresponding to our virtual directory).
  3. Invoke Recycle method in the DirectoryServices entry corresponding to the application pool.

I divided the code into this 3 steps, the RecycleApplicationPool method can be used separately for recycling any application pool (by knowing only its name). The RecycleCurrentApplicationPool method returns a boolean value indicating if the application pool was recycled.

public static class ApplicationPoolRecycle
{
    /// <summary>Attempts to recycle current application pool</summary>
    /// <returns>Boolean indicating if application pool was successfully recycled</returns>
    public static bool RecycleCurrentApplicationPool()
    {
        try
        {
            // Application hosted on IIS that supports App Pools, like 6.0 and 7.0
            if (IsApplicationRunningOnAppPool())
            {
                // Get current application pool name
                string appPoolId = GetCurrentApplicationPoolId();
                // Recycle current application pool
                RecycleApplicationPool(appPoolId);
                return true;
            }
            else
                return false;
        }
        catch
        {
            return false;
        }
    }

    private static bool IsApplicationRunningOnAppPool()
    {
        // Application is not hosted on IIS
        if (!AppDomain.CurrentDomain.FriendlyName.StartsWith("/LM/"))
            return false;
        // Application hosted on IIS that doesn't support App Pools, like 5.1
        else if (!DirectoryEntry.Exists("IIS://Localhost/W3SVC/AppPools"))
            return false;
        else
            return true;
    }

    private static string GetCurrentApplicationPoolId()
    {
        string virtualDirPath = AppDomain.CurrentDomain.FriendlyName;
        virtualDirPath = virtualDirPath.Substring(4);
        int index = virtualDirPath.Length + 1;
        index = virtualDirPath.LastIndexOf("-", index - 1, index - 1);
        index = virtualDirPath.LastIndexOf("-", index - 1, index - 1);
        virtualDirPath = "IIS://localhost/" + virtualDirPath.Remove(index);
        DirectoryEntry virtualDirEntry = new DirectoryEntry(virtualDirPath);
        return virtualDirEntry.Properties["AppPoolId"].Value.ToString();
    }

    private static void RecycleApplicationPool(string appPoolId)
    {
        string appPoolPath = "IIS://localhost/W3SVC/AppPools/" + appPoolId;
        DirectoryEntry appPoolEntry = new DirectoryEntry(appPoolPath);
        appPoolEntry.Invoke("Recycle");
    }
}

VN:F [1.9.11_1134]
Rating: 5.0/5 (1 vote cast)
.NET C#: Recycle current Application Pool programmatically (for IIS 6+), 5.0 out of 5 based on 1 rating
  1. May 7, 2008 9:19 PM | #1

    Hola Leandro, curso al igual con vos en la UTN y queria saber si tenés conocimientos en MSSQL y PHP orientado a objetos. Ya que en la empresa que estoy trabajando andamos en busqueda de programadores de medio tiempo ( mañana o tarde, dependiendo en el horario que curses) Si te intereza, tenés mi mail.

    Saludos,
    Pablo.-

    VA:F [1.9.11_1134]
    Rating: 0 (from 0 votes)
  2. Name
    July 8, 2008 4:37 PM | #2

    Can you be more specific about which libraries should be included for this code?

    VA:F [1.9.11_1134]
    Rating: 0 (from 0 votes)
  3. leandrodg
    July 8, 2008 5:04 PM | #3

    Of course, the only “rare” one is System.DirectoryServices, available from Add Reference menu => .NET Assemblies.

    I’ve updated this to work with WMI instead of DirectoryServices (because of problems with computers where DirectoryServices didn’t work correctly), the only problem is that only IIS 6+ expose to WMI (so XP IIS 5.1 won’t work).

    I’ll try to post it ASAP.

    VA:F [1.9.11_1134]
    Rating: 0 (from 0 votes)
  4. mchern
    September 10, 2008 7:42 PM | #4

    What rights/permissions IIS user should have to avoid the Access Denied exception on attempt to Call any-thing on the DirectoryEntry?

    VA:F [1.9.11_1134]
    Rating: 0 (from 0 votes)
  5. Pachu
    October 7, 2008 4:06 PM | #5

    Hi, (nos juntamos varios de la UTN parece)…

    I have a related question, i have some class library, published with a WCF service application in IIS 6. This class library has some worker threads doing stuff.

    How can i receive an event (or something like) when the AppPool of the WCF Service App is recycled to do save, restore, cleanup code…

    Thanks che!

    VA:F [1.9.11_1134]
    Rating: 0 (from 0 votes)
  6. Eric Le Guehennec
    August 28, 2009 7:51 AM | #6

    What rights/permissions should be set to avoid the UnauthorizedAccessException on appPoolEntry.Invoke(“Recycle”) ?

    VA:F [1.9.11_1134]
    Rating: +1 (from 1 vote)
  7. Paresh
    July 27, 2012 9:50 AM | #7

    Not working well for me! getting unknown-error-0×80005000

    VA:F [1.9.11_1134]
    Rating: 0 (from 0 votes)
  1. April 7th, 2011 at 15:27 | #1