How to kill process by name in C#
By FoxLearn 10/10/2024 4:04:23 AM 123
// 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.
- How to fix 'Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on'
- How to use BlockingCollection in C#
- Calculating the Distance Between Two Coordinates in C#
- Could Not Find an Implementation of the Query Pattern
- Fixing Invalid Parameter Type in Attribute Constructor
- Objects added to a BindingSource’s list must all be of the same type
- How to use dictionary with tuples in C#
- How to convert a dictionary to a list in C#