Recycle application pool programatically

By steve, 8 December, 2011

We have an application pool that gets unhappy, and the ODBC and/or active directory lookups start to fail until the application pool has been recycled. to fix the problem I was able to add the following code to get an ASP.NET page to recycle its own application pool:

DirectoryEntry ApplicationSite = new DirectoryEntry("IIS://" + System.Environment.MachineName + Request.ServerVariables["APPL_MS_PATH"].Substring(3));
string AppPoolName = ApplicationSite.Properties["AppPoolId"].Value.ToString();
DirectoryEntry Application = new DirectoryEntry("IIS://" + System.Environment.MachineName + AppPoolName);
Application.Invoke("Recycle", null);

This does require that the application pool user has certain permissions on the local machine. I have not determined the exact permissions required, but can confirm that it works when running as administrator (which is a bad idea for security reasons), and does not work for the default app pool user.

Tags

Comments