using System; using System.Collections.Generic; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; namespace SafeMobileLib { public class ServiceControlUtils { /// /// Start a service by it's name /// /// public static void startService(string ServiceName) { try { ServiceController sc = new ServiceController(); sc.ServiceName = ServiceName; Utils.WriteLine(String.Format("The {0} service status is currently set to {1}", ServiceName, sc.Status.ToString())); if (sc.Status == ServiceControllerStatus.Stopped) { // Start the service if the current status is stopped. Utils.WriteLine(String.Format("Starting the {0} service ...", ServiceName)); try { // Start the service, and wait until its status is "Running". sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running); // Display the current service status. Utils.WriteLine(String.Format("The {0} service status is now set to {1}.", ServiceName, sc.Status.ToString()), ConsoleColor.Magenta); } catch (InvalidOperationException e) { Utils.WriteLine(String.Format("Could not start the {0} service.", ServiceName), ConsoleColor.Red); Utils.WriteLine(e.Message); } } else { Utils.WriteLine(String.Format("Service {0} already running.", ServiceName), ConsoleColor.DarkRed); } } catch (Exception ex) { Utils.WriteLine(String.Format("Could not start the {0} service. Because: " + ex.ToString(), ServiceName), ConsoleColor.Red); } } /// /// Stop a service that is active /// /// public static void stopService(string ServiceName) { try { ServiceController sc = new ServiceController(); sc.ServiceName = ServiceName; Utils.WriteLine(String.Format("The {0} service status is currently set to {1}", ServiceName, sc.Status.ToString())); if (sc.Status == ServiceControllerStatus.Running) { // Start the service if the current status is stopped. Utils.WriteLine(String.Format("Stopping the {0} service ...", ServiceName)); try { // Start the service, and wait until its status is "Running". sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped); // Display the current service status. Utils.WriteLine(String.Format("The {0} service status is now set to {1}.", ServiceName, sc.Status.ToString()), ConsoleColor.Magenta); } catch (InvalidOperationException e) { Utils.WriteLine(String.Format("Could not stop the {0} service.", ServiceName), ConsoleColor.Red); Utils.WriteLine(e.Message); } } else { Utils.WriteLine(String.Format("Cannot stop service {0} because it's already inactive.", ServiceName), ConsoleColor.DarkRed); } } catch(Exception ex) { Utils.WriteLine(String.Format("Could not stop the {0} service. Because: " + ex.ToString(), ServiceName) , ConsoleColor.Red); } } public static bool IsServiceRunning(string ServiceName) { try { ServiceController sc = new ServiceController(); sc.ServiceName = ServiceName; if (sc.Status == ServiceControllerStatus.Running) { return true; } else { return false; } } catch { return false; } } } }