Kill some processes by .exe file name

后端 未结 6 821
情深已故
情深已故 2020-11-27 02:45

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

相关标签:
6条回答
  • 2020-11-27 03:01

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

    Process processToKill = Process.GetProcessById(pid);
    processToKill.Kill();
    
    0 讨论(0)
  • 2020-11-27 03:03
    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%.

    0 讨论(0)
  • 2020-11-27 03:05

    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();
    }
    
    0 讨论(0)
  • 2020-11-27 03:09

    Quick Answer:

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

    (leave off .exe from process name)

    0 讨论(0)
  • 2020-11-27 03:10

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

    0 讨论(0)
  • 2020-11-27 03:17

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

    0 讨论(0)
提交回复
热议问题