How to start or stop a service using C#
We can start a service using C#.Basically we need a service name and service startup type that we have to provide to start or stop.Here i will give an example to start a service .
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);
}
)
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
//strtpending etc.. other than stopped)
//Replace s.Start(); with t.Stop();
NOTE:References to be added
1.System.Management
2.System.ServiceProcess
Namespace to be added:
using System.Management;
Good one.
Keep it up.
++
Thanks and Regards.
Meetu Choudhary.
Site Coordinator.