Restart IIS Application Pool with C#

How to restart IIS with C# code

To check Application Pool we will use library Microsoft.Web.Administration.dll


public void RestartAppPool(string appPool, out bool isRun)
        {
            isRun = true;
            try
            {
                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();
                            Thread.Sleep(3000);
                            if (pool.State == ObjectState.Stopped)
                                isRun = false;
                            else
                            {                                
                                
                            }
                        }

                        if (process != null)
                        {
                            for (int i = 0; i < 5; i++)
                            {
                                if (!process.HasExited)
                                {
                                    // Discard cached information about the process.
                                    process.Refresh();
                                    // Print working set to console.                                  
                                    // Wait 2 seconds.
                                    Thread.Sleep(2000);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {                        
                    }
                }               
            }
            catch (Exception ex)
            {               
            }
        }
        
Reactions

Post a Comment

0 Comments