首页 > 代码库 > C#重启IIS指定网站和指定应用程序池
C#重启IIS指定网站和指定应用程序池
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading; 6 using System.IO; 7 using Microsoft.Web.Administration; 8 9 10 namespace RecoveryWebSite 11 { 12 class Program 13 { 14 const string AppPoolName = "POD"; 15 const string WebSiteName = "POD"; 16 const int SleepTime = 1000 * 60; 17 18 static void Main(string[] args) 19 { 20 21 Thread tAppPool = new Thread(() => RecoveryAppPool()); 22 tAppPool.IsBackground = true; 23 tAppPool.Start(); 24 25 Thread tWebSite = new Thread(() => RecoveryWebSite()); 26 tWebSite.IsBackground = true; 27 tWebSite.Start(); 28 29 //防止程序退出 30 while (true) 31 { 32 Thread.Sleep(SleepTime); 33 } 34 } 35 36 static void RecoveryAppPool() 37 { 38 while (true) 39 { 40 var sm = new ServerManager(); 41 var pool = sm.ApplicationPools[AppPoolName]; 42 if (pool != null && pool.State == ObjectState.Stopped) 43 { 44 WriteLog("检测到应用池" + AppPoolName + "停止服务"); 45 WriteLog("正在启动应用池" + AppPoolName); 46 if (pool.Start() == ObjectState.Started) 47 { 48 WriteLog("成功启动应用池" + AppPoolName); 49 } 50 else 51 { 52 WriteLog("启动应用池" + AppPoolName + "失败. " + SleepTime / 60 + "秒后重试启动"); 53 } 54 } 55 sm.Dispose(); 56 sm = null; 57 Thread.Sleep(SleepTime); 58 } 59 } 60 61 static void RecoveryWebSite() 62 { 63 while (true) 64 { 65 var sm = new ServerManager(); 66 var site = sm.Sites[WebSiteName]; 67 if (site != null && site.State == ObjectState.Stopped) 68 { 69 WriteLog("检测到网站" + WebSiteName + "停止服务"); 70 WriteLog("正在启动网站" + WebSiteName); 71 if (site.Start() == ObjectState.Started) 72 { 73 WriteLog("成功启动网站" + WebSiteName); 74 } 75 else 76 { 77 WriteLog("启动网站" + WebSiteName + "失败. " + SleepTime / 60 + "秒后重试启动"); 78 } 79 } 80 sm.Dispose(); 81 sm = null; 82 Thread.Sleep(SleepTime); 83 } 84 } 85 86 static void WriteLog(string msg) 87 { 88 var fPath = "c:\\RecoveryWebsiteLog.txt"; 89 if (!File.Exists(fPath)) 90 { 91 File.Create(fPath).Close(); 92 } 93 94 using (StreamWriter sw = new StreamWriter(fPath, true, Encoding.UTF8)) 95 { 96 sw.WriteLine(string.Format("{0} , 时间{1}", msg, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"))); 97 } 98 } 99 }100 }
注意:
Microsoft.Web.Administration 命名空间,可以通过Nuget包管理器找到并添加.
这个启动网站和应用池的功能也可以通过cmd 给 appcmd.exe发送命令,读取cmd执行后的返回值来实现
有待改进的地方:
1,没做成服务.
2,程序运行时间长,内存会有略微的增加,不知道什么原因.
C#重启IIS指定网站和指定应用程序池
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。