Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a process using command line code

Tags:

c#

I am working on a c# winforms application. I am trying to close a running process by its process ID.

try
{
  //Find process & Kill
  foreach (Process Proc in (from p in Process.GetProcesses()
                            where p.ProcessName == "taskmgr" || p.ProcessName == "explorer"
                            select p))
  {
    Microsoft.VisualBasic.Interaction.Shell("TASKKILL /F /IM " + Proc.ProcessName + ".exe");
  }
}
catch (Exception ex)
{
  ErrorLogging.WriteErrorLog(ex);
}
return null;

This code is not working on windows 2003 SP 2. I have googled and found that 2003 does not have the taskkill command. What would be a substitute for that?

like image 530
Sonam Mohite Avatar asked Apr 08 '26 20:04

Sonam Mohite


1 Answers

Use the Process.Kill method. If you have the required permission it will work.

Process.Kill Method Immediately stops the associated process.

Sample

try
{
    //Find process
    foreach (Process Proc in (from p in Process.GetProcesses()
                                where p.ProcessName == "taskmgr" ||
                                    p.ProcessName == "explorer"
                                select p))
    {
        // "Kill" the process
        Proc.Kill();
    }
}
catch (Win32Exception ex)
{
    // The associated process could not be terminated.
    // or The process is terminating.
    // or The associated process is a Win16 executable.
    ErrorLogging.WriteErrorLog(ex);
}
catch (NotSupportedException ex)
{
    // You are attempting to call Kill for a process that is running on a remote computer. 
    // The method is available only for processes running on the local computer.
    ErrorLogging.WriteErrorLog(ex);
}
catch (InvalidOperationException ex)
{
    // The process has already exited.
    // or There is no process associated with this Process object.
    ErrorLogging.WriteErrorLog(ex);
}
return null;

More Information

  • MSDN - Process.Kill Method
like image 170
dknaack Avatar answered Apr 10 '26 09:04

dknaack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!