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";
To 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
// call to start the Application Pool
// call to recycle the Application Pool
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. Let me know, if you have any queries on that. I am available on Twitter and Facebook. Don’t forget to connect with me.