문제

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

도움이 되었습니까?

해결책

Quick Answer:

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

(leave off .exe from process name)

다른 팁

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%.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top