1. App.config 配置
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<appSettings>
<!--发送的邮件地址-->
<add key ="mailaddress" value="发送者的邮箱地址"/>
<!--发送的邮件的密码-->
<add key="mailpassword" value="发送者的邮箱密码"/>
<!--邮件发送给谁-->
<add key="mailto" value="通知接收人的邮箱"/>
<!--发送邮件的内容-->
<add key="mailcontent" value="windows 服务已停止,并已自动启动"/>
<!--发送邮件的标题-->
<add key="mailtitle" value="服务死掉提醒"/>
<add key="sip" value="smtp.126.com"/>
</appSettings>
</configuration>
2.主要代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.ServiceProcess;
using System.Configuration;
using System.Net.Mail;
using System.Net;
namespace Test
{
class Program
{
private static object _lock = new object();
//时间间隔
private const int _trimerInterval = 20000;
//监视服务名称
private const string MyServiceName = "MongoDB";
private static System.Timers.Timer _trimer = new Timer();
static void Main(string[] args)
{
_trimer.Interval = _trimerInterval;
_trimer.Enabled = true;
_trimer.Elapsed += _trimer_Elapsed;
Console.WriteLine("正在开启服务。。。。");
Console.Read();
}
/// <summary>
/// 事件间隔事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void _trimer_Elapsed(object sender, ElapsedEventArgs e)
{
//检测指定服务是否开启,如停止则发送邮件通知用户并自动开启
if (!CheckService(MyServiceName))
{
//开启服务
StartService(MyServiceName);
}
}
/// <summary>
/// 检测服务是否正常
/// </summary>
/// <param name="serviceName">检测的服务名称</param>
/// <returns>返回 bool(true或false)</returns>
private static bool CheckService(string serviceName)
{
bool result = true;
try
{
lock (_lock)
{
//获取本机所有的服务
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController service in services)
{
if (service.ServiceName.Trim() == serviceName.Trim())
{
//判断服务状态(Stopped:服务停止, StopPending:服务正在停止) <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
if ((service.Status == ServiceControllerStatus.Stopped) || (service.Status == ServiceControllerStatus.StopPending))
{
result = false;
System.Threading.Thread.Sleep(10000);
//服务已停止,发送邮件给通知
SendMail();
return result;
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return result;
}
/// <summary>
/// 开启指定服务
/// </summary>
/// <param name="serviceName">检测的服务名称</param>
private static void StartService(string serviceName)
{
try
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController service in services)
{
if (service.ServiceName.Trim() == serviceName.Trim())
{
//开启服务
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 30));
Console.WriteLine("服务已成功开启");
return;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
/// <summary>
/// 发送邮件
/// </summary>
public static void SendMail()
{
//发送的邮箱地址
var emailAcount = ConfigurationManager.AppSettings["mailaddress"];
//发送的邮箱密码
var emailPassword = ConfigurationManager.AppSettings["mailpassword"];
//发送给谁
var to = ConfigurationManager.AppSettings["mailto"];
//发送内容
var content = ConfigurationManager.AppSettings["mailcontent"];
//邮件标题
var mailtitle = ConfigurationManager.AppSettings["mailtitle"];
//邮件服务器
var mailservice = ConfigurationManager.AppSettings["sip"];
//创建邮件发送实例
MailMessage message = new MailMessage();
//设置发件人,发件人需要与设置的邮件发送服务器的邮箱一致
MailAddress fromAddr = new MailAddress(emailAcount);
message.From = fromAddr;
//设置收件人,可添加多个,添加方法与下面的一样
message.To.Add(to);
//设置邮件标题
message.Subject = mailtitle;
//设置邮件内容
message.Body = content;
//设置邮件发送服务器,服务器根据你使用的邮箱而不同,可以到相应的 邮箱管理后台查看,下面是QQ的
SmtpClient client = new SmtpClient(mailservice, 25);
//设置发送人的邮箱账号和密码
client.Credentials = new NetworkCredential(emailAcount, emailPassword);
//启用ssl,也就是安全发送
client.EnableSsl = true;
//发送邮件
client.Send(message);
}
}
}
结果却出现了问题
原来是没有获得管理员权限,可做如下操作
项目名称-->属性---安全性
解决