How to start or stop a service using C#


private void StartService()

{

System.ServiceProcess.ServiceController[] allService = System.ServiceProcess.ServiceController.GetServices();

foreach (System.ServiceProcess.ServiceController s in allService)

{

if (s.ServiceName.Equals("Alerter"))

{

if (s.Status.Equals(System.ServiceProcess.ServiceControllerStatus.Stopped))//check service staus

{

bool status = ServiceStartModeUpdate("Alerter", "Manual", "Can't start service");//provide service name here and startup Type that must be automatic or manual

if (status == true)

{

s.Start();

}

}

}

}

}

private bool ServiceStartModeUpdate(string serviceName, string startMode,string errorMsg)

{

uint successReturn = 1;

errorMsg = string.Empty;

string filterService =String.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", serviceName);

ManagementObjectSearcher querySearch = new ManagementObjectSearcher(filterService);

if (querySearch == null)// if match not found

{

return false;

}

else

{

try

{

ManagementObjectCollection services = querySearch.Get();//get that service

foreach (ManagementObject service in services)

{

if (Convert.ToString(service.GetPropertyValue("StartMode")) == "Disabled")//if startup type is Diasabled then change it

{

ManagementBaseObject inParams =service.GetMethodParameters("ChangeStartMode");

inParams["startmode"] = startMode;

ManagementBaseObject outParams =service.InvokeMethod("ChangeStartMode", inParams, null);

successReturn = Convert.ToUInt16(outParams.Properties["ReturnValue"].Value);

}

}

}

catch (Exception ex)

{

errorMsg = ex.Message;

throw;

}

}

return (successReturn == 0);

}

NOTE:

Just make some changes to stop a service as well.
Replace if (s.Status.Equals
(System.ServiceProcess.ServiceControllerStatus.Stopped)) with if
(s.Status.Equals(System.ServiceProcess.ServiceControllerStatus.Running)or
start,pending etc.. other than stopped)
Replace s.Start(); with t.Stop();

References to be added

1.System.Management 
2.System.ServiceProcess 

Namespace to be added:

using System.Management;

Comments