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
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();
}
}
}
}
}
}
}
Process.GetProcessesByName("service name") does not work in my case bu 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With