0

I would like to run all the .exe files in a certain directory from my winform application.

Is there a way not to hard code the file path of each exe and be not dependent on knowing beforehand how many exe I have to run?

Loathing
  • 4,887
  • 3
  • 20
  • 32
  • 1
    Does this answer your question? [Directory.GetFiles of certain extension](https://stackoverflow.com/questions/13301053/directory-getfiles-of-certain-extension) – Leo Rossetti Sep 14 '20 at 07:17

3 Answers3

0
//get exe files included in the directory
var files = Directory.GetFiles("<target-directory>", "*.exe"); 

Console.WriteLine("Number of exe:" + files.Count());

foreach (var file in files)
{
    // start each process
    Process.Start(file);
}
Derviş Kayımbaşıoğlu
  • 26,360
  • 3
  • 47
  • 64
0
            DirectoryInfo d = new DirectoryInfo(filepath);

            foreach (var file in d.GetFiles("*.exe"))
            {
                Process.Start(file.FullName);
            }
Joeri E
  • 101
  • 9
0

You can get all executable files using:

static public List<string> GetAllExecutables(string path)
{
  return Directory.Exists(path)
         ? Directory.GetFiles(path, "*.exe").ToList()
         : return new List<string>(); // or null
}

You can run one with:

static public Process RunShell(string filePath, string arguments = "")
{
  try
  {
    var process = new Process();
    process.StartInfo.FileName = filePath;
    process.StartInfo.Arguments = arguments;
    process.Start();
    return process;
  }
  catch ( Exception ex )
  {
    Console.WriteLine($"Can''t run: {filePath}{Environment.NewLine}{Environment.NewLine}" +
                      ex.Message);
    return null;
  }
}

Thus you can write:

foreach ( string item in GetAllExecutables(@"c:\MyPath") )
  RunShell(item);