Sunday 13 November 2011

Manage IIS Application Pool from .Net C# code

  .Net framework provides a very easy-to-use API wrapper class, ServerManager, to help manage IIS system from any .Net application using either C# or VB.net. Below C# code snippet demonstrates how to restart/recycle a given AppPool in IIS.
     
    public void RestartAppPool(string appPool)
        {
            try
            {
                logger.Info("Restarting app pool: " + appPool);

                // Recycle app pool
                using (var manager = new ServerManager())
                {
                    var pool = manager.ApplicationPools[appPool];

                    if (pool != null) 
                    {
                        Process process = null;

                        if (pool.WorkerProcesses.Count > 0)
                        {
                            process = Process.GetProcessById(pool.WorkerProcesses[0].ProcessId);
                        }

                        if (pool.State == ObjectState.Stopped)
                            pool.Start();
                        else
                            pool.Recycle();

                        // clean up any worker thread created by app pool
                        if (process != null)
                        {
                            while (!process.HasExited)
                            {
                                Thread.Sleep(10);
                            }

                            process.Dispose();
                        }
                    }
                }

                //logger.Info("Successfully restarted app pool: " + appPool);
            }
            catch (Exception ex)
            {
               // logger.Error("Restart app pool error: " + ex);
            }
        }
 

3 comments: