Reputation: 193
I need help to kill a windows service using C#, now to kill the service use the following option:
From the cmd:
sc queryex ServiceName
After discovering the PID
of the service
taskkill /pid 1234(exemple) /f
Upvotes: 4
Views: 9960
Reputation: 789
Process.GetProcessesByName("service name") does not work in my case but the below does. You will need references to System.ServiceProcess and to System.Management.
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;
}
Upvotes: 2
Reputation: 413
Here the code uses 4 methods to stop your service including TaskKill, note that you must have sufficient privilege to do so.
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)
});
}
}
}
}
}
}
}
}
}
Upvotes: 1
Reputation: 6552
For ease of reading but I would separate the services interactions into it's own class with separate methods IsServiceInstalled, IsServiceRunning, StopService ..etc if you get what I mean.
Also by stopping the service it should kill the process already but I included how you would do something like that as well. If the service won't stop and you are stopping it by killing the process, I would look at the service code if you have access to it wasn't built correctly.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceProcess;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ServiceController sc = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName.Equals("MyServiceNameHere"));
if (sc != null)
{
if (sc.Status.Equals(ServiceControllerStatus.Running))
{
sc.Stop();
Process[] procs = Process.GetProcessesByName("MyProcessName");
if (procs.Length > 0)
{
foreach (Process proc in procs)
{
//do other stuff if you need to find out if this is the correct proc instance if you have more than one
proc.Kill();
}
}
}
}
}
}
}
Upvotes: 5
Reputation: 520
If you know the process id use Process.GetProcessById(Id).Kill(); If you know the process name use Process.GetProcessesByName(name).Kill();
Upvotes: 1