Home > Back-end >  Winform how to run an exe file in a folder without knowing the name?
Winform how to run an exe file in a folder without knowing the name?

Time:11-15

Ok, so im making a program launcher, but the file im trying to run have a random name. Heres my code, it works but when the name changes to something random it will stop working

private void button1_Click(object sender, EventArgs e)
    {
            Process process = new Process()
            {
                StartInfo = new ProcessStartInfo(Environment.CurrentDirectory   "/Files/330637421.exe")
                {
                    WindowStyle = ProcessWindowStyle.Normal,
                    WorkingDirectory = Path.GetDirectoryName(Environment.CurrentDirectory   "/Files/")
                }

            };
            process.Start();
    }

Now its working because my file is called 330637421.exe but it will trow an exception because the file will not exist if it changes the name . Btw it is the only exe file on the Files folder. Is there any way to run every exe file on that folder? also keeping the workingdirectory

CodePudding user response:

You can use GetFiles method to get the file. But you have to be careful if there are multiple files in this path. Then you can use pattern to get the particular file.

You can use the required overloaded method mentioned in the documentation.

CodePudding user response:

Here's an example grabbing the first returned file from Directory.GetFiles():

String folder = System.IO.Path.Combine(Environment.CurrentDirectory, "Files");
if (System.IO.Directory.Exists(folder))
{
    String executable = System.IO.Directory.GetFiles(folder, "*.exe").FirstOrDefault();
    if (executable != null)
    {
        Process process = new Process()
        {
            StartInfo = new ProcessStartInfo(executable)
            {
                WindowStyle = ProcessWindowStyle.Normal,
                WorkingDirectory = folder
            }
        };
        process.Start();

    }
    else
    {
        MessageBox.Show("No .EXE found in the ../Files Folder!");
    }
}
else
{
    MessageBox.Show("No ../Files Folder Exists!");
}
  • Related