Introduction
The need for programmatically executing an IIS application pool recycle can arise for a number of reasons. It happened to me when I was developing a WF (Windows workflow) activity to deploy the code to IIS virtual directory where I force an app pool recycle after deployment. After doing a lot of search, I found the API (Microsoft.Web.Administration.dll) that provides most of the features like start, stop, recycle functions, etc.
Namespace: Microsoft.Web.Administration
The API can be found in %WinDir%\system32\Inetsrv\Microsoft.Web.Administration.dll.
Assembly: Microsoft.Web.Administration
(in Microsoft.Web.Administration.dll)
Namespace: Microsoft.Web.Administration
The Microsoft.Web.Administration
namespace consist of classes that can be used to administer IIS. This API provides lots of functionality like read and write configuration information of ApplicationHost.config, Web.config, and Administration.config files.
Also API can be used for creating a site, starting or stopping a site, deleting an application pool, recycle, start and stop an application pool, etc.
Add Reference with the Help of Nuget
You can use the below command to install the Microsoft.Web.Administration
DLL reference with the help of nugget package console.
Install-Package Microsoft.Web.Administration
Recycle All Available Pools
API provides the following main classes to play with the IIS app pools.
ServerManager
ApplicationPoolCollection
ApplicationPool
Following are the steps that we need to follow to recycle all available pools in IIS.
Step 1. Add the Microsoft.Web.Administration
DLL to your class from %WinDir%\system32\Inetsrv\Microsoft.Web.Administration.dll or through nuget (as mentioned above).
Step 2. Create a function to where you are going to recycle all app pools. Now use the below mentioned code to get the app pools and recycle them one by one.
Server Manager class initializes the new instance by using the default path of the ApplicationHost.config file.
In the same way, you can use the start
and stop
functions.
public static void RecycleAppPools()
{
ServerManager serverManager = new ServerManager();
ApplicationPoolCollection appPools = serverManager.ApplicationPools;
foreach (ApplicationPool ap in appPools)
{
ap.Recycle();
}
}
Recycle a Particular Pool
Follow the same steps given above. Only difference here is that instead of getting all the app pools, get the specified pool from the app pool collection as shown in the below code:
public static void RecycleAppPool()
{
ServerManager serverManager = new ServerManager();
ApplicationPool appPool = serverManager.ApplicationPools["Test_AppPool"];
if (appPool != null)
{
if (appPool.State == ObjectState.Stopped)
{
appPool.Start();
}
else
{
appPool.Recycle();
}
}
}