C#重启IIS指定网站和指定应用程序池

using Jinher.AMP.BTP.Deploy;
using Microsoft.Web.Administration;
using Redis.Helper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Redis
{

public class Program
{
static readonly string AppPoolName = ConfigurationManager.AppSettings["ApplicationPoolName"].ToString();
static readonly string WebSiteName = ConfigurationManager.AppSettings["WebSiteName"].ToString();
static readonly int SleepTime = int.Parse(ConfigurationManager.AppSettings["SleepTime"].ToString());
static ServerManager sm;

static void Main(string[] args)
{
Console.WriteLine($"检测程序启动,【{WebSiteName}】当网站或其应用池停下后,会自动启动。");
sm = new ServerManager();
new Thread(RecoveryWebSite).Start();
}

static void RecoveryWebSite()
{
while (true)
{
try
{
var pool = sm.ApplicationPools[AppPoolName];
if (pool != null && pool.State == ObjectState.Stopped)
{
Console.WriteLine("检测到应用池" + AppPoolName + "停止服务");
Console.WriteLine("正在启动应用池" + AppPoolName);
if (pool.Start() == ObjectState.Started)
{
Console.WriteLine("成功启动应用池" + AppPoolName);
}
else
{
Console.WriteLine("启动应用池" + AppPoolName + "失败. " + SleepTime / 60 + "秒后重试启动");
}
}

var site = sm.Sites[WebSiteName];
if (site != null && site.State == ObjectState.Stopped)
{
Console.WriteLine("检测到网站" + WebSiteName + "停止服务");
Console.WriteLine("正在启动网站" + WebSiteName);
if (site.Start() == ObjectState.Started)
{
Console.WriteLine("成功启动网站" + WebSiteName);
}
else
{
Console.WriteLine("启动网站" + WebSiteName + "失败. " + SleepTime / 60 + "秒后重试启动");
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}

GC.Collect();
Thread.Sleep(SleepTime);
}
}
}
}

原文地址:https://www.cnblogs.com/zoujinhua/p/11934227.html