1. App. Config configuration
<?xml version= "1.0" encoding= "Utf-8"?><configuration> <startup> <supportedruntime version= "v4.0" sku= ". netframework,version=v4.5.2 "/> </startup> <appSettings> <!--email address -- <add key = "mailaddress" value= "sender's email address"/> <!--The password for the message sent-- <add key= "MailPassword" value= " Sender's email password "/> <!--mail to whom-- <add key=" mailto "value=" notify Recipient's mailbox "/> <!--send Message Content-- <add key= "mailcontent" value= "Windows service stopped and started automatically"/> <!--send headers-- <add key= " Mailtitle "value=" Service Dead reminder "/> <add key=" sip "value=" smtp.126.com "/> </appsettings></ Configuration>
2. Main code
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 (); Time interval Private Const int _trimerinterval = 20000; Monitoring Service Name 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 ("Opening service ....") "); Console.read (); }///<summary>//Event interval events///</summary>//<param name= "Sender" ></para m>//<param name= "E" ></param> private static void _trimer_elapsed (Object SendeR, Elapsedeventargs e) {//detect if the specified service is turned on, or if it is stopped, send an email notifying the user and automatically turn on the IF (! Checkservice (myServiceName)) {//Open service StartService (myservicename); }}///<summary>///Detection service is normal///</summary>//<param name= "Servicena Me > Service Name detected </param>//<returns> return bool (TRUE or FALSE) </returns> private static bool Chec Kservice (string serviceName) {bool result = true; try {Lock (_lock) {//Get native all services Servicecon troller[] Services = servicecontroller.getservices (); foreach (ServiceController service in services) {if (service. Servicename.trim () = = Servicename.trim ()) {//Judge service status (Stopped: Service stopped, StopP Ending: Service is stopping) <requestedexecutionlevel Level= "Requireadministrator" uiaccess= "false"/> if (service. Status = = servicecontrollerstatus.stopped) | | (Service. Status = = servicecontrollerstatus.stoppending)) {result = False ; System.Threading.Thread.Sleep (10000); Service has stopped, send mail to Notification SendMail (); return result; }}}}} catch (Exception ex) { Console.WriteLine (ex. ToString ()); } return result; }///<summary>///<param Name= "ServiceName" > Detected service Service name </param> private static void StartService (string serviceName) {try { Servicecontroller[] ServiCES = servicecontroller.getservices (); foreach (ServiceController service in services) {if (service. Servicename.trim () = = Servicename.trim ()) {//Open service Servic E.start (); Service. WaitForStatus (servicecontrollerstatus.running, New TimeSpan (0, 0, 30)); Console.WriteLine ("Service has been successfully opened"); Return }}} catch (Exception ex) {Console.WriteLine (ex). ToString ()); }}///<summary>///Send mail///</summary> public static void SendMail () {//e-mail address var emailacount = configurationmanager.appsettings["MailAddress"]; Sent email password var emailpassword = configurationmanager.appsettings["MailPassword"]; Send to who var to = Configurationmanager.appsettings["mailto"]; Send contents var content = configurationmanager.appsettings["Mailcontent"]; Message title var mailtitle = configurationmanager.appsettings["Mailtitle"]; Mail server var mailservice = configurationmanager.appsettings["SIP"]; Create message Send instance MailMessage message = new MailMessage (); To set the sender, the sender needs to be consistent with the mailbox set for the mail-sending server mailaddress fromaddr = new MailAddress (emailacount); Message. from = FROMADDR; To set up recipients, you can add multiple, and add the same method as the following message. To.add (to); Sets the message header of the messages. Subject = Mailtitle; Sets the message content of the messages. Body = content; Set up the mail sending server, the server according to your use of the mailbox and different, can go to the corresponding mailbox management Backstage view, the following is the QQ smtpclient client = new SmtpClient (Mailservice, 25); Set the sender's email account and password client. Credentials = new NetworkCredential (Emailacount, Emailpassword); Enable SSL, which is to send the client securely. Enablessl = tRue Send mail client. Send (message); } }}
And there was a problem.
The original is not get administrator rights, can do the following actions
Project name--Property---security
Solve
"C #" Windows Service daemon and send mail notification