文章技术适合初学者。高级的C#开发工程师这些估计都熟悉到烂了,望不要喷。
第一、C#代码要操作IIS 就必须先导入 Microsoft.Web.Administration.dll ,方便控制台程序做成windows服务,还要导入Topshelf.dll,附件中有这两个dll,
想要玩一下的可以下载试试,点击Install.bat做windows服务,也可以直接点击exe文件在控制台上查看您要的效果, 点击下载附件.
第二、整个小工具就两个类,Program.cs , IISWatcherControl.cs 直接贴代码了,这个小工具只是为了帮您自动重启IIS,但是程序为什么会崩溃或者 程序池会挂掉,
还是要您自己检查下写的代码哪里写的不合理导致的.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using Topshelf;
-
- namespace IISWatcherService
- {
- class Program
- {
- static void Main(string[] args)
- {
- HostFactory.Run((x) =>
- {
- x.Service<IISWatcherControl>();
- x.RunAsLocalSystem();
- x.SetServiceName("IISWatcherService");
- x.SetDisplayName("IISWatcherService");
- x.SetDescription("监控IIS运行状态");
- });
- }
- }
- }
C#监控IIS代码
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using Microsoft.Web.Administration;
- using Topshelf;
-
- namespace IISWatcherService
- {
- public class IISWatcherControl : ServiceControl
- {
-
- #region ServiceControl 成员
-
- public bool Start(HostControl hostControl)
- {
- MonitoringIISApp();
- return true;
- }
-
- public bool Stop(HostControl hostControl)
- {
- return true;
- }
- /// <summary>
- /// 每个十秒钟监控一次是否有暂停的web站点和应用程序池
- /// </summary>
- public void MonitoringIISApp()
- {
- ServerManager webIIS = new ServerManager();
- Task.Factory.StartNew(() =>
- {
- var result = string.Empty;
- while (true)
- {
- //获取IIS站点
- var sites = webIIS.Sites;
- foreach (var item in sites)
- {
- if (item.Bindings.Any(ii => ii.Protocol != "ftp") && item.State == ObjectState.Stopped)
- {
- if (item.Start() == ObjectState.Started)
- {
- result = string.Format(item.Name + ",站点启动成功 {0}",DateTime.Now);
- Console.WriteLine(result);
- WriteFile(result);
- }
- }
- }
- //获取应用程序池
- var applications = webIIS.ApplicationPools;
- foreach (var item in applications)
- {
- if (item.State == ObjectState.Stopped)
- {
- if (item.Start() == ObjectState.Started)
- {
- result = string.Format(item.Name + ",应用程序池开启成功 {0}", DateTime.Now);
- Console.WriteLine(result);
- WriteFile(result);
- }
- }
- }
- Thread.Sleep(TimeSpan.FromSeconds(10d));
- }
- });
- }
/// <summary>
/// 日志写入文件
/// </summary>
private void WriteFile(string message)
{
-
- var directorypath = AppDomain.CurrentDomain.BaseDirectory + @"\LogFile";
- if (!Directory.Exists(directorypath))
- {
- Directory.CreateDirectory(directorypath);
- }
- var path = string.Format(directorypath + @"\log_{0}.txt", DateTime.Now.ToString("yyyyMMdd"));
- if (!File.Exists(path))
- {
- File.Create(path).Close();
- }
- using (StreamWriter sw=new StreamWriter(path,true,System.Text.Encoding.UTF8))
- {
- sw.WriteLine(message);
- }
- }
-
- #endregion
- }
- }
时间飞快2017年一下就过去了,这是2018年的第一篇文章,希望今年可以写些博文。