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添加 .