foreach (ServiceController Svc in ServiceController.GetServices())
{
using (Svc)
{
//The short name of "Microsoft Exchange Service Host"
if (Svc.ServiceName.Equals("YourServiceName"))
{
if (Svc.Status != ServiceControllerStatus.Stopped)
{
if (Svc.CanStop)
{
try
{
Svc.Stop();
Svc.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 15));
}
catch
{
//Try to stop using Process
foreach (Process Prc in Process.GetProcessesByName(Svc.ServiceName))
{
using (Prc)
{
try
{
//Try to kill the service process
Prc.Kill();
}
catch
{
//Try to terminate the service using taskkill command
Process.Start(new ProcessStartInfo
{
FileName = "cmd.exe",
CreateNoWindow = true,
UseShellExecute = false,
Arguments = string.Format("/c taskkill /pid {0} /f", Prc.Id)
});
//Additional:
Process.Start(new ProcessStartInfo
{
FileName = "net.exe",
CreateNoWindow = true,
UseShellExecute = false,
Arguments = string.Format("stop {0}", Prc.ProcessName)
});
}
}
}
}
}
}
}
}
}
public static void Kill()
{
int processId = GetProcessIdByServiceName(ServiceName);
var process = Process.GetProcessById(processId);
process.Kill();
}
private static int GetProcessIdByServiceName(string serviceName)
{
string qry = $"SELECT PROCESSID FROM WIN32_SERVICE WHERE NAME = '{serviceName }'";
var searcher = new ManagementObjectSearcher(qry);
var managementObjects = new ManagementObjectSearcher(qry).Get();
if (managementObjects.Count != 1)
throw new InvalidOperationException($"In attempt to kill a service '{serviceName}', expected to find one process for service but found {managementObjects.Count}.");
int processId = 0;
foreach (ManagementObject mngntObj in managementObjects)
processId = (int)(uint) mngntObj["PROCESSID"];
if (processId == 0)
throw new InvalidOperationException($"In attempt to kill a service '{serviceName}', process ID for service is 0. Possible reason is the service is already stopped.");
return processId;
}