In this post we will learn how to manage IIS Application Pool programmatically using C# .NET. Here we will learn how to stop, start and recycle the pool.
-
Published by Kunal Chowdhury
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 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.
Solution Architect & Former Microsoft MVP
Kunal Chowdhury is an enterprise solution architect and former multi-year Microsoft MVP. He is the author of three technical books: Windows Presentation Foundation Development Cookbook, Mastering Visual Studio 2017, and the Mastering Visual Studio 2019.
He publishes technical articles on Kunal-Chowdhury.com.