How to kill a process and all its derived processes in C#

Lionsure 2020-08-24 Original by the website

There are many different processes in a system, it may involve one process killing another process or killing another process and all the processes derived from it. A simple and common situation is software update. After the update process has downloaded the update files, the main process must be closed, that is, the main process and all its derived processes must be killed, and then the files replacement update will be performed.

No matter what programming language provides a method to kill a process, the following uses C# as an example to illustrate the method of killing a process. First introduce how to kill a process, and then introduce a process to kill another process and all its derived processes.

 

1. How to kill a process and all all its derived processes by name in C#(How to kill a program)

There is a method to get the process and all its derived processes according to the process name in C#. As long as the processes are got by this method, they can be killed one by one. The implementation code is as follows:

using System.Diagnostics;

/// <summary>
       /// C# kill a process and all its derived processes after closing a program
       /// </summary>
       /// <param name="processName">The name of the process to be killed</param>

       public void CloseProcesses(string processName)
       {
              Process[] arrPro = Process.GetProcessesByName(processName);
              foreach (Process pro in arrPro)
                     vpro.Kill();
       }

Call: CloseProcesses("softName");

 

 

2. C# kill all processes

The method is similar to killing a process and its derived processes, except that the method of getting the process is different. The former needs to be got based on the process name, while the latter is to get all processes without the process name. The implementation code is as follows:

using System.Diagnostics;

/// <summary>
       /// C# kill all processes
       /// </summary>

       public void KillProcesses()
       {
              Process[] arrPro = Process.GetProcesses();
              foreach (Process p in arrPro)
                     p.Kill();
       }

Call: KillProcesses();