Advertisement
Foxy1986

Service checker/forcer

Sep 25th, 2018
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.76 KB | None | 0 0
  1. /*
  2. Monitor a running service on system
  3. if it's not running, it will start it automatically
  4. and respectively, if it stops, it will start it again after refresh rate */
  5.  
  6. using System;
  7. using System.Linq;
  8. using System.ServiceProcess;
  9.  
  10.  
  11. namespace ServiceMonitor
  12. {
  13.     class Program
  14.     {
  15.         public static bool ServiceExists(string ServiceName)
  16.         {
  17.             return ServiceController.GetServices().Any(serviceController => serviceController.ServiceName.Equals(ServiceName));
  18.         }
  19.  
  20.         public static void Main(string[] args)
  21.         {
  22.             System.Console.Title = "Service monitor coded by Foxy";
  23.             string serviceName;
  24.             System.Console.Write("Enter the service name to monitor: ");
  25.             serviceName = System.Console.ReadLine();
  26.  
  27.            
  28.             while (true)
  29.             {
  30.                 ServiceController sc = new ServiceController(serviceName);
  31.  
  32.  
  33.                 try
  34.                 {
  35.  
  36.                     if (sc.Status == ServiceControllerStatus.Running)
  37.                     {
  38.                         System.Console.WriteLine("Sweet, monitoring service, if it stops I'll start it for you.");
  39.                     }
  40.  
  41.                     else if (sc.Status == ServiceControllerStatus.Stopped)
  42.                     {
  43.  
  44.                         System.Console.WriteLine("WARNING, service not running, restarting now");
  45.  
  46.                         System.Threading.Thread.Sleep(7000);
  47.                         sc.Start();
  48.                     }
  49.  
  50.  
  51.                     System.Threading.Thread.Sleep(30000);
  52.                 }
  53.                 catch (Exception e) { System.Console.WriteLine("Can't find service with that name, close and try again"); Console.ReadKey(); break; };
  54.             }
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement