C# 重启IIS站点及应用程序池

    static void Main(string[] args)
	{
		Console.WriteLine("检测程序启动运行,自动启动或停止网站及应用池。");
		new Thread(RecoveryWebSite).Start();//开启线程
	}
	/// 
	/// 停止/启动iis站点
    /// 
    public static void RecoveryWebSite()
    {
    	const string AppPoolName = "";//iis应用程序池名称
		const string WebSiteName = "";//iis网站名称
		const int SleepTime = 1000 * 30;//间隔事件:每30秒执行一次
		ServerManager sm = new ServerManager();
		while (true)
		{
			try
			{
				var pool = sm.ApplicationPools[AppPoolName];//根据应用程序池名称获取
				if (pool != null)
				{
					if (pool.State == ObjectState.Stopped)
					{
						WriteLog("检测到应用池" + AppPoolName + "停止服务");
						WriteLog("正在启动应用池" + AppPoolName);
						if (pool.Start() == ObjectState.Started)
						{
							WriteLog("成功启动应用池" + AppPoolName);
						}
						else
                        {
							WriteLog("启动应用池" + AppPoolName + "失败. " + SleepTime / 60 + "秒后重试启动");
						}
					}
					else if (pool.State == ObjectState.Started)
					{
						if (pool.Stop() == ObjectState.Stopped)
						{
                        	WriteLog("成功停止应用池" + AppPoolName);
                        }
                        else
	                    {
                        	WriteLog("停止应用池" + AppPoolName + "失败. " + SleepTime / 60 + "秒后重试启动");
                        }
					}
				}
				Site site = sm.Sites[WebSiteName];//根据网站名称获取IIS站点
				if (site != null)
				{
					if (site.State == ObjectState.Stopped)
					{
						WriteLog("检测到网站" + WebSiteName + "停止服务");
						WriteLog("正在启动网站" + WebSiteName);
						if (site.Start() == ObjectState.Started)
						{
							WriteLog("成功启动网站" + WebSiteName);
						}
						else
						{
							WriteLog("启动网站" + WebSiteName + "失败. " + SleepTime / 60 + "秒后重试启动");
						}
					}
					else if (site.State == ObjectState.Started)
					{
						if (site.Stop() == ObjectState.Stopped)
						{
							WriteLog("成功停止网站" + AppPoolName);
						}
						else
						{
							WriteLog("停止网站" + AppPoolName + "失败. " + SleepTime / 60 + "秒后重试启动");
						}
					}
				}
			}
			catch (Exception ex)
			{
				WriteLog(ex.Message.ToString());
			}
			GC.Collect();
			Thread.Sleep(SleepTime);//暂停运行
		}
	}  
	/// 
	/// 写日志
	/// 
	/// 
	public static void WriteLog(string msg)
	{
		var fPath = "C:\\Users\\Administrator\\Desktop\\更新日志.txt";
		if (!File.Exists(fPath))
		{
			File.Create(fPath).Close();
		}
		using (StreamWriter sw = new StreamWriter(fPath, true, Encoding.UTF8))
		{
			sw.WriteLine(string.Format("{0} , 时间{1}", msg, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")));
		}
	} 

你可能感兴趣的:(.net,c#,开发语言)