How to kill process by name in C#

By FoxLearn 10/10/2024 4:04:23 AM   123
To kill a process by name in C#, you can use the System.Diagnostics namespace, which provides the Process class.
// Specify the process name without the .exe extension
string processName = "notepad"; // Example: "notepad" for Notepad.exe

// Get all processes with the specified name
Process[] processes = Process.GetProcessesByName(processName);

// Iterate through each process and kill it
foreach (Process process in processes)
{
    process.Kill();
    process.WaitForExit(); // Optional: wait for the process to exit
}

Make sure to include System.Diagnostics to access the Process class.

You can replace "notepad" with the name of the process you want to kill, excluding the .exe extension.

The Process.GetProcessesByName(processName) retrieves all processes with the specified name.

The Kill() method terminates the process, and WaitForExit() can be used to wait for the process to fully exit.

You can also create a KillProcess method to help you kill your process name.

public void KillProcess(string processName)
{
    var process = Process.GetProcessesByName(processName);
    foreach (var p in process)
    {
        p.Kill();
        p.WaitForExit();
    }
}

To kill a process by name asynchronously using C# 8 Async Enumerables, you can leverage asynchronous programming to handle multiple processes without blocking the main thread.

For example:

string processName = "WINWORD"; // without '.exe'
await Process.GetProcesses()
             .Where(x => x.ProcessName == processName)
             .ToAsyncEnumerable()
             .ForEachAsync(p => p.Kill());

Make sure you have the necessary permissions to kill the specified process, as some processes may require elevated privileges.