Question

How can I kill some active processes by searching for their .exe filenames in C# .NET or C++?

Was it helpful?

Solution

Quick Answer:

foreach (var process in Process.GetProcessesByName("whatever"))
{
    process.Kill();
}

(leave off .exe from process name)

OTHER TIPS

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 want to use async approach with some useful recent methods from the C# 8 (Async Enumerables), then check this:

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, but at least it will not waste the CPU time and will prevent the foreground thread from hanging while doing the operations. In any case, you need to think about what version you might want.

You can use Process.GetProcesses() to get the currently running processes, then Process.Kill() to kill a process.

If you have the process ID (PID) you can kill this process as follow:

Process processToKill = Process.GetProcessById(pid);
processToKill.Kill();

You can Kill a specific instance of MS Word.

foreach (var process in Process.GetProcessesByName("WINWORD"))
{
    // Temp is a document which you need to kill.
    if (process.MainWindowTitle.Contains("Temp")) 
        process.Kill();
}
public void EndTask(string taskname)
{
      string processName = taskname.Replace(".exe", "");

      foreach (Process process in Process.GetProcessesByName(processName))
      {
          process.Kill();
      }
}

//EndTask("notepad");

Summary: no matter if the name contains .exe, the process will end. You don't need to "leave off .exe from process name", It works 100%.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top