-1

What's the easiest method to killing all apps running under a folder and all of its subfolders using WinForms?

I would try killing individual processes but that would be less efficient and if more get added to that folder then I'd have to update my code every time.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • What do you have so far? – Charlieface May 21 '23 at 20:43
  • I have the code to straight up kill a program, but I need to get a piece of code that will go through a folder and all of its subfolders and find every file ending with .exe and add it to an array, I can do the rest myself. – Dwayne_The_Rock_Johnson May 21 '23 at 20:46
  • 1
    Please show what you have. Why do you need to read the files in the folder, why not just search through running processes for ones which match the path? – Charlieface May 21 '23 at 20:47
  • Now that I think about it, that would probably work better. I just need to make sure it'd work for everything in any subfolders too. Here's my code to kill an app: foreach (var process in Process.GetProcessesByName("notepad")) { process.Kill(); } – Dwayne_The_Rock_Johnson May 21 '23 at 21:55

2 Answers2

0

I would also kill processes via process name to ensure a given process is terminated on various paths. However you can do something like:

string processPath = @"c:\blablabla";

Process[] currentProcesses = Process.GetProcesses();
foreach (Process process in currentProcesses)
{
    if (process.MainModule != null &&
        process.MainModule.FileName == processPath)
    {
        process.Kill();
    }
}
jmvcollaborator
  • 2,141
  • 1
  • 6
  • 17
0

You can use the MainModule property to get the path for every process, then just check if it starts with your path.

Don't forget to dispose the process objects when done.

var processes = Process.GetProcesses();
try
{
    foreach (var process in processes)
    {
        try
        {
            if (process.MainModule?.FileName?.StartsWith(yourPath, StringComparison.OrdinalIgnoreCase) ?? false)
                process.Kill();
        }
        catch
        { //
        }
    }
}
finally
{
    foreach (var process in processes)
        process.Dispose();
}
Charlieface
  • 52,284
  • 6
  • 19
  • 43