Kill some processes by .exe file name
You can use Process.GetProcesses()
to get the currently running processes, then Process.Kill()
to kill a process.
My solution is to use Process.GetProcess()
for listing all the processes.
By filtering them to contain the processes I want, I can then run Process.Kill()
method to stop them:
var chromeDriverProcesses = Process.GetProcesses().
Where(pr => pr.ProcessName == "chromedriver"); // without '.exe'
foreach (var process in chromeDriverProcesses)
{
process.Kill();
}
Update:
In case if you want to do the same in an asynchronous way (using the C# 8
Async Enumerables
), check this out:
const string processName = "chromedriver"; // without '.exe'
await Process.GetProcesses()
.Where(pr => pr.ProcessName == processName)
.ToAsyncEnumerable()
.ForEachAsync(p => p.Kill());
Note: using async
methods doesn't always mean code will run faster.
The main benefit is that the foreground thread will be released while operating.
Quick Answer:
foreach (var process in Process.GetProcessesByName("whatever"))
{
process.Kill();
}
(leave off .exe from process name)