Gal Ratner
Gal Ratner is a Techie who lives and works in Los Angeles. linked
How to start and stop windows services on local and remote computers

ServiceController is a usfull class located in System.ServiceProcess namespace. We can use ServiceController to get a list of services running on your local, or remore comuters. We can start, stop, pause and continue services from your code.

Getting a list of services:

public static List<string> GetServices(string machineName)

        {

            if (!string.IsNullOrEmpty(machineName))

                return ServiceController.GetServices(machineName).Select((ServiceController sc) => sc.ServiceName).ToList();

            return ServiceController.GetServices().Select((ServiceController sc) => sc.ServiceName).ToList();

        }

Starting a service

public static ServiceControllerStatus StartService(string serviceName, string machineName)

        {

            ServiceController sc = null;

            if (!string.IsNullOrEmpty(machineName))

                sc = new ServiceController(serviceName, machineName);

            else

                sc = new ServiceController(serviceName);

            if (sc.Status.Equals(ServiceControllerStatus.Stopped) || sc.Status.Equals(ServiceControllerStatus.StopPending))

            {

                sc.Start();

            }

            return sc.Status;

        }


Stopping a service

public static ServiceControllerStatus StopService(string serviceName, string machineName)

        {

            ServiceController sc = null;

            if (!string.IsNullOrEmpty(machineName))

                sc = new ServiceController(serviceName, machineName);

            else

                sc = new ServiceController(serviceName);

            if (sc.Status.Equals(ServiceControllerStatus.Running) || sc.Status.Equals(ServiceControllerStatus.StartPending))

            {

                sc.Stop();

            }

            return sc.Status;

        }


Posted 4 Dec 2009 5:40 AM by Gal Ratner
Filed under: ,

Powered by Community Server (Non-Commercial Edition), by Telligent Systems