Search code examples
c#.netwindows-services

Get the PID of a Windows service


Could anyone help me to know how to get the PID of a Windows service?
I need to get the PID in order to run the following command:

Process.Start(new ProcessStartInfo 
    {
        Filename = "cmd.exe",
        CreateNoWindow = true,
        UseShellExecute = false,
        Arguments = string.Format("/c taskkill /pid {0} /f", pidnumber)
    });

Solution

  • Assuming you know the name of the EXE the service uses and there is exactly one of them:

    int procID = Process.GetProcessesByName("yourservice")[0].Id;
    

    The method Process.GetProcessesByName("yourservice") returns an Array of Processes with your specified name, so in case you don't know how much of "yourservice.exe" runs simultaneously you might need a foreach loop.