How to kill process by name in C#
By FoxLearn 10/10/2024 4:04:23 AM 38
// 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 Read data from Google Sheet in C# using HttpRequest without Speadsheet API
- How to set DataSource for RDLC Report using Report Viewer in C#
- How to Change report in ReportViewer at runtime in C#
- C# Tutorial
- How to Create overlay modal popup in C#
- How to check if file exists on Server in C#
- How to encrypt a password in C#
- How to read excel file in C#