How to Start, Stop, Recycle IIS application pool programmatically?

IIS application pool defines a set of web applications and their corresponding worker processes to provide a convenient way to administer a set of web sites and applications. Sometime developers need to programmatically start, stop or recycle the IIS application pool.

 

In this post, we will learn how to programmatically call the directory service to invoke the start, stop and recycle operation on IIS server.

 

Like all websites present in IIS server, the application pool also has a specific URL. It uses “IIS:” protocol to communicate with the server. The URL consists of SERVER_NAME, a generic path and the name of the application pool.

 

Here is the structure of the application pool URL (don’t forget to change the SERVER_NAME and APP_POOL_NAME):

 

private const string APPLICATION_POOL_URL = "IIS://SERVER_NAME/W3SVC/AppPools/APP_POOL_NAME";

 

Application Pool in IISTo load the pool, you need to use the class “DirectoryEntry” present under the namespace “System.DirectoryServices” which encapsulates a node or object in the Active Directory Domain Services hierarchy. It has a method called Invoke(…), which calls the native Active Directory Domain Services object.

 

The Invoke(…) method takes the method name as the parameter which you want to call on that domain service object. The second parameter takes arguments to that method. If you want to stop the Application pool, set the first parameter to “Stop”. In case of start or recycle, just use “Start” or “Recycle” respectively.

 

Here is a code snippet that will guide you creating the DirectoryEntry object and calling the Invoke(…) method with proper parameter to do specific operation with the IIS application pool:

 

const string APPLICATION_POOL_URL = "IIS://KUNAL-CHOWDHURY.COM/W3SVC/AppPools/BlogPool";
var directoryEntry = new DirectoryEntry(APPLICATION_POOL_URL, USERNAME, PASSWORD);
 
// call to stop the Application Pool
directoryEntry.Invoke("Stop", null);
 
// call to start the Application Pool
directoryEntry.Invoke("Start", null);
 
// call to recycle the Application Pool
directoryEntry.Invoke("Recycle", null);

 

Hope this small post will help you if you want to do Start, Stop or Recycle operation programmatically in any of your IIS application pool.

Have a question? Or, a comment? Let's Discuss it below...

dhgate

Thank you for visiting our website!

We value your engagement and would love to hear your thoughts. Don't forget to leave a comment below to share your feedback, opinions, or questions.

We believe in fostering an interactive and inclusive community, and your comments play a crucial role in creating that environment.