using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.IO; using Microsoft.Web.Administration; namespace RecoveryWebSite { public class Program { const string AppPoolName = "POD"; const string WebSiteName = "POD"; const int SleepTime = 1000 * 30; static ServerManager sm; static void Main(string[] args) { Console.WriteLine("检测程序启动,当POD网站或其应用池停下后,会自动启动。"); 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) { WriteLog("检测到应用池" + AppPoolName + "停止服务"); WriteLog("正在启动应用池" + AppPoolName); if (pool.Start() == ObjectState.Started) { WriteLog("成功启动应用池" + AppPoolName); } else { WriteLog("启动应用池" + AppPoolName + "失败. " + SleepTime / 60 + "秒后重试启动"); } } var site = sm.Sites[WebSiteName]; if (site != null && site.State == ObjectState.Stopped) { WriteLog("检测到网站" + WebSiteName + "停止服务"); WriteLog("正在启动网站" + WebSiteName); if (site.Start() == ObjectState.Started) { WriteLog("成功启动网站" + WebSiteName); } else { WriteLog("启动网站" + WebSiteName + "失败. " + SleepTime / 60 + "秒后重试启动"); } } } catch (Exception ex) { WriteLog(ex.Message.ToString()); } GC.Collect(); Thread.Sleep(SleepTime); } } static void WriteLog(string msg) { var fPath = "c:\\RecoveryWebsiteLog.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"))); } //GC.Collect(); } } }
Microsoft.Web.Administration命名空间,可以用nuget添加 .