0

I'm trying to:

1) get a list of all executables in a directory and all subdirectories.

2) if any of those executables is running, kill the process.

What I have so far:

String[] exes =
Directory.GetFiles("C:\\Temp", "*.EXE", SearchOption.AllDirectories)
.Select(fileName => Path.GetFileNameWithoutExtension(fileName))
.ToArray();

{
    exes.ToList().ForEach(Console.WriteLine);
}

Console.ReadLine();

So this shows me a list of the executables. How do I use this list to kill the processes, if they are running?

imsome1
  • 1,182
  • 4
  • 22
  • 37
bRins
  • 83
  • 9
  • see https://stackoverflow.com/questions/648410/how-can-i-list-all-processes-running-in-windows – rene Oct 03 '17 at 08:43
  • 1
    Should you not turn this around and instead enumerate all processes and kill them if (the primary/any) module's path is within that directory structure? Is there a reason to want/not expect that there could be an exe running that has loaded a DLL from that directory but that process should be exempted from killing? – Damien_The_Unbeliever Oct 03 '17 at 08:45
  • I used https://stackoverflow.com/questions/3899864/what-process-locks-a-file as a basis to rewrite fuser for windows.. allows you to itterate processes for a given file, with some tweeking you could change it to work with a number of files you got from your file list – BugFinder Oct 03 '17 at 09:09
  • @Damien_The_Unbeliever I'm just learning C#, so forgive my ignorance. Why would that be better, and how would that look, code-wise? – bRins Oct 03 '17 at 09:26

1 Answers1

1

Ended up with this:

                    try
                {
                    //Find exes in dir and subdirs
                    String[] exes =
                    Directory.GetFiles("C:\\Temp", "*.EXE", SearchOption.AllDirectories)
                    .Select(fileName => Path.GetFileNameWithoutExtension(fileName))
                    .AsEnumerable()
                    .ToArray();

                    // kill the process if it is in the list 
                    var runningProceses = Process.GetProcesses();
                    for (int i = 0; i < runningProceses.Length; i++)
                    {

                     if (exes.Contains(runningProceses[i].ProcessName))
                     {
                      runningProceses[i].Kill(); 
                     }

                    }


                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
bRins
  • 83
  • 9