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?
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?
DirectoryInfo d = new DirectoryInfo(filepath);
foreach (var file in d.GetFiles("*.exe"))
{
Process.Start(file.FullName);
}
//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);
}
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);