Reputation: 13
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.
Upvotes: 1
Views: 1092
Reputation: 3352
FileName is just the filename of the executable. You have to pass any arguments in the Arguments property.
E.g.
killTask.StartInfo.FileName = @"C:\Windows\System32\taskkill.exe";
killTask.StartInfo.Arguments = @"/f /pid " + pid;
Upvotes: 0
Reputation: 343
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;
}
Upvotes: 1