Kill some processes by .exe file name
Asked Answered
P

9

179

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

Pugging answered 27/7, 2010 at 15:42 Comment(1)
If you need kill process by partial name see #14632662.Yestreen
B
315

Quick Answer:

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

(leave off .exe from process name)

Boigie answered 27/7, 2010 at 15:48 Comment(7)
what should be do if above code return Exception (a 32 bit processes cannot access modules of a 64 bit process) ?Caco
Leave off ".exe". From MSDN: "The process name is a friendly name for the process, such as Outlook, that does not include the .exe extension or the path"Bonnes
Is Kill safe as Environment.Exit(0)?Inverse
@Inverse Process.Kill() sends a kill signal to a process, which will halt its execution wherever it happens to be. This is different from an interrupt signal in that the process will not have a chance to respond and/or clean up from the signal. No more execution will happen in that process, and any locks on resources used by that process will be released. Environment.Exit() is performed by the currently executing process to kill itself with a success code, which is perfectly safe. Process.Kill() is not nearly as safe as Environment.Exit().Tarshatarshish
I suggest the use of LINQ: var procs = Process.GetProcesses().Where(pr => pr.ProcessName.Contains("Spotify"));Brianabriand
Any option to kill a specific instance of a process? I mean, Contains("Spotify")) kills all the instances of Spotify. I want to kill a particular instance of Spotify.Bozen
@BaneeIshaqueK I had a similar requirement, I had used MainWindowTitle to find the right process and used CloseMainWindow to close it. You can try itLeahleahey
E
62

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.

Ehlers answered 27/12, 2013 at 12:47 Comment(3)
you could use Contains instead of equalBrianabriand
Funny coincidence is, I was looking in this thread for a solution to killing the chromedriver. Must be a common issue.Ashlar
Same here. that doesn't seem to solve it though. The initial console that gets fired off is actually an instance of chrome.exe and I'm guessing you don't want to force close all of those unless its a build/test agentArbe
I
20

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

Immobility answered 27/7, 2010 at 15:45 Comment(2)
Process.GetProcessesByName would simplify this.Boigie
what should be do if above code return Exception (a 32 bit processes cannot access modules of a 64 bit process) ?Caco
N
2

Depending on how many processes there are to kill (e.g. when its hundreds like in my case), foreaching over all of them might take quite a while. (interesting sidenote: while Kill() was usually quite quick in .NET FW 4.8 , somehow in NET 6.0 Windows its a lot slower - seeing multiple Win32Exceptions in the debug/trace until the target process is finally done)

Anyway back to topic: In case of an app shutdown, where u need to make sure every process is is gone, consider using the TAP library - particulary the Parallel shortcuts, hundreds of processes killed within a glimpse.

Usage example:

var procs = Process.GetProcessByName("mydirtyprocesses");

if (procs.Length == 0) return;

procs.AsParallel().ForAll(process => 
{
   try
   {
      process.Kill();

   // No process linked to the process comp (mostly because the process died in 
   // the short timespan between invoking GetProcess() and the effective 
   // initialization of the props/fields of the component. -OR- Process has 
   // already exited (when the exit happened after the process component has 
   // beenpopulated (difference is, in case 1 you cannot even get the Process 
   // ID from // the component, in case 2 you see data like Id and get the true 
   // for HasExited // - so always be prepared for that.
   // catch (InvalidOperationException) 
   {
     // Process is gone, no further action required
     return;
   }

   // Ensuring process is gone (otherwise try again or fail or whatever)
   if (!process.HasExited)
   { 
       // Handle it
   }
}

In this particular scenario just wrap it properly in try/catch , as with such a number of processes the probability for an exception is quite increased

Neutralize answered 15/1, 2022 at 22:51 Comment(0)
F
1

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();
}
Fromm answered 27/7, 2010 at 15:43 Comment(0)
L
1

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

Process processToKill = Process.GetProcessById(pid);
processToKill.Kill();
Lajoie answered 22/4, 2019 at 8:7 Comment(0)
A
1

For my part, I wanted to be sure to catch the right process... ;-)

So I do:

private static void KillProcessesByPath(string fullExePath)
{
  var processName = Path.GetFileNameWithoutExtension(fullExePath);

  foreach (var process in Process.GetProcessesByName(processName))
  {
    if (process.MainModule?.FileName != fullExePath) continue;

    process.Kill();
  }
}
Attentive answered 23/8, 2023 at 7:14 Comment(0)
C
0
static void Main()
    {
        string processName = Process.GetCurrentProcess().ProcessName;
        int processId = Process.GetCurrentProcess().Id;
        
        Process[] oProcesses = Process.GetProcessesByName(processName);

        if (oProcesses.Length > 1)
        {
            if ((MessageBox.Show("Application is opened!", "",MessageBoxButtons.YesNo) == DialogResult.Yes)) ;
            {
                foreach (var process in Process.GetProcessesByName(processName))
                {
                    if (process.Id != processId)
                    {
                        process.Kill();
                    }
                }
            }
        }
        else
        {   
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmLogin());
        }
    }
California answered 27/2, 2022 at 16:2 Comment(0)
S
-1
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%.

Scribbler answered 9/6, 2017 at 20:59 Comment(3)
a simple .Replace(".exe", "") on the top voted answer would do this with a lot less convoluted and unnecessary codeThelmathem
The whole idea of it is to see the method with or without .exe so people can see multiple ways of handling it... It's not meant for copy and paste....Scribbler
this won't work if the name actually contains ".exe" e.g. "my.exeption.exe" Alternatively you could check substring of last four characters.. although again that would fail for a name with "my.exe.exe". Just pointing it out.Legal

© 2022 - 2025 — McMap. All rights reserved.