How to kill process by name in C#
By FoxLearn 3/4/2025 3:05:38 AM 653
// 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.
For example, c# kill process by name
// process kill by 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.
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization