Search code examples
c#web-servicespid

C# - Method for killing a process/task using PID


I'm trying to create a webservice using C# that will be used to kill a process/task that is currently running. Whenever I try to run it and enter the correct PID to kill that specific task, I get this error message "System.ComponentModel.Win32Exception: 'The system cannot find the file specified'".

public string KillTask(int pid)
    {
        Process killTask = new Process();
        killTask.StartInfo.FileName = (@"C:\Windows\System32\taskkill.exe /f /pid "  + pid);
        killTask.StartInfo.RedirectStandardOutput = true;
        killTask.StartInfo.UseShellExecute = false;
        killTask.Start();
        killTask.WaitForExit();

        return "";
    }

The error message highlights killTask.Start() but I don't quite understand why the system cannot find the file.


Solution

  • If you want to kill the Process(?), you could easily do

    var processToKill = Process.GetProcessById(pid);
    processToKill.Kill();
    

    Or with a return value (why you want string?)

    public bool KillTask(int pid)
    {
        try
        {
            var processToKill = Process.GetProcessById(pid);
        }
        catch (ArgumentException) //Exception when no process found
        {
            return false;
        }
    
        processToKill.Kill();
        return true;
    }