繁体   English   中英

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!");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM