Start, Stop, Recycle IIS 8 Application Pool using C# or ASP.Net MVC
We use Internet Information Service mainly to host APS.NET websites in an organization. There might be use cases where we might have to restart or manage an IIS Application Pool using a C# application or APS.NET Core / MVC applications. This article about how we can manage an IIS Application pool to recycle/stop/start using C#.
Note: The method explained here is applicable for both IIS 7 and IIS 8
The Micosoft.Web.Administration library provides necessary end-points/functions to manage a full IIS server. The library can be included to the project in two ways.
1. Manually adding reference to your project. The library can be found in the path C:\Windows\System32\inetsrv, if this folder is empty make sure you have enabled Internet Information Service from Programs and Features in control panel.
2. Add Micosoft.Web.Administration as NuGet package to your solution.
Starting IIS Application Pool using C#:
The ServerManager class present in the library Microsoft.Web.Administration provides us access to the application pools. The below code is used to start an IIS Application Pool.
var yourAppPool=new ServerManager().ApplicationPools["Your_App_Pool_Name"]; if(yourAppPool!=null) yourAppPool.Start();
Stopping/Recycling IIS Application Pool using C#:
Replace yourAppPool.Start(); with yourAppPool.Stop(); to stop the application pool and yourAppPool.Recycle(); to recycle the pool.
Starting All IIS Application Pools using C#:
ServerManager().ApplicationPool returns an array of all the available application pools. We can use loop to iterate over each item and call the execute the function Start() to start the pools.
foreach(var x in new ServerManager().ApplicationPools) x.Start();
Retrieving IIS Application Pool running state using C#:
The ApplicationPool class provides an property State to retrieve the current state of an pool. An enumeration of ObjectState will be returned the State Property.
var state=new ServerManager().ApplicationPools["Your_App_Pool_Name"].State;
Starting = 0
Started = 1
Stopping = 2
Stopped = 3
Unknown = 4