2

I need to find a way to kill all processes that use a certain image path. I have been finding that killing the process by name doesn't always kill the process properly - due to the fact that its developers are unable to keep the same name from build to build.

I have done some digging around, but haven't been able to find a solution to this. Wondering if someone here can point me in the right direction.

4444
  • 3,541
  • 10
  • 32
  • 43

3 Answers3

3
Process.GetProcesses()
        .First(p => String.Compare(p.MainModule.FileName,filename,true)==0)
        .Kill();
I4V
  • 34,891
  • 6
  • 67
  • 79
  • This throws "access denied" when it runs into system processes. – Chrsjkigs99 Aug 08 '13 at 19:19
  • only if filename points to a systemprocess, but it will throw a NullReference Exception if there is no Process running with the specified filename – makim Aug 08 '13 at 19:23
2

this would kill all Processes that runs in the specific directory

System.Diagnostics.Process.GetProcesses()
.Where(p => Path.GetDirectoryName(p.MainModule.FileName).ToLower().Equals(path.ToLower())
.ToList().ForEach(p => p.Kill());
makim
  • 3,154
  • 4
  • 30
  • 49
  • You're missing a bracket. `.Where(p => Path.GetDirectoryName(p.MainModule.FileName).ToLower().Equals(path.ToLower())**)**` – Fadeway Jan 27 '17 at 22:05
1

I believe this is what you want

var imagePath = @"C:\applicationfolder";
var processes = Process.GetProcesses()
                .Where(p => p.MainModule.FileName.StartsWith(imagePath, true, CultureInfo.InvariantCulture));
foreach (var proc in processes)
{
    proc.Kill();
}
Charles380
  • 1,269
  • 8
  • 19
  • 2
    ShaneSuperflyMacNeill, put your application in folder `C:\P` or `C:\W` and have fun :) – I4V Aug 08 '13 at 19:30
  • heh, I'm not arguing about best practices lol. Just doing what he wanted. Yes `C:\P` or `C:\W` would be quite humorous when everything just shuts down. – Charles380 Aug 08 '13 at 19:36
  • that worked perfectly. Although I am unsure what CultureInfo.InvariantCulture is, don't think I have used it before so MSDN will be my next stop :) – Shane Superfly MacNeill Aug 08 '13 at 19:36
  • It's used to determine how the strings are compared by culture. http://msdn.microsoft.com/en-us/library/6k0axhx9.aspx – Charles380 Aug 08 '13 at 19:38
  • well I have had to drop this as it gives an exception error "Unable to enumerate the process modules" not sure how to fix that. – Shane Superfly MacNeill Aug 08 '13 at 21:58
  • @I4V Just use a backslash at the end of the folder name and you do not have this problem -> C:\P\ – Harry13 Jul 20 '18 at 10:04