SpoKe
SpoKe

Reputation: 121

C# - Killing a process by a part of it's name

I'm searching for how to do it in C#, like this :

foreach (Process proc in Process.GetProcessesByName("cheatengine-x86_64"))
{
    proc.Kill();
}

I am using this statement, but there are different versions of the program, like just cheatengine or cheatengine-x86, I'd like to close any of these, by starting with the name 'cheat', or just 'cheate', just to avoid the older versions.

Upvotes: 12

Views: 12313

Answers (5)

J.T. Taylor
J.T. Taylor

Reputation: 4277

using System.Diagnostics;

Process.GetProcesses()
    .Where(x => x.ProcessName.StartsWith("cheate", StringComparison.OrdinalIgnoreCase))
    .ToList()
    .ForEach(x => x.Kill());

Upvotes: 16

Sowmiya R
Sowmiya R

Reputation: 78

This will kill the process when it contains specific string

System.Diagnostics.Process.GetProcesses()
                         .Where(x => x.ProcessName.ToLower()
                                      .Contains("chrome"))
                         .ToList()
                         .ForEach(x => x.Kill());

Upvotes: -1

Aniket Inge
Aniket Inge

Reputation: 25705

You can iterate through each process name, then match it with a regexp and then kill it if it matches.

Regex regex = new Regex(@"cheate.*");
 foreach (Process p in Process.GetProcesses(".")){
    if(regex.Matches(p.ProcessName))
      p.Kill();
 }

something like this.

The advantage of this is, you can kill any process that starts with or ends with a particular regular expression.

Upvotes: 6

Gray
Gray

Reputation: 7130

adapted from here: http://www.howtogeek.com/howto/programming/get-a-list-of-running-processes-in-c/

using System.Diagnostics;


Process[] processlist = Process.GetProcesses();

foreach(Process theprocess in processlist)
{

    if(theprocess.ProcessName.StartsWith("cheat");
         theprocess.Kill(); 
}

This is just a rough idea, you can use any method you want to match the process. I recommend something that ignores case, but I would be very cautious with false positives. I would not be happy with your program if it closed something it shouldn't.

Upvotes: 4

Pablo Romeo
Pablo Romeo

Reputation: 11396

Use Process.GetProcesses() and use Linq to filter the ones that you want to kill.

Upvotes: 1

Related Questions