Winform 如何在不知道名称的情况下 运行 文件夹中的 exe 文件?

Winform how to run an exe file in a folder without knowing the name?

好的,所以我正在制作一个程序启动器,但我试图 运行 的文件有一个随机名称。这是我的代码,它可以工作,但是当名称更改为随机名称时它将停止工作

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();
    }

现在可以使用了,因为我的文件名为 330637421.exe,但它会抛出异常,因为如果更改名称,文件将不存在。顺便说一句,它是 Files 文件夹中唯一的 exe 文件。有什么办法 运行 该文件夹中的每个 exe 文件吗?还保留工作目录

您可以使用GetFiles方法获取文件。但是如果这个路径中有多个文件,你就得小心了。然后你可以使用模式来获取特定的文件。

您可以使用文档中提到的所需重载方法。

这是一个从 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!");
}