You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Winform如何运行指定文件夹内名称未知的exe,解决文件名随机变更后报错问题

你可以先遍历获取Files目录下的所有exe文件,再逐个启动即可,修改后的代码如下:

private void button1_Click(object sender, EventArgs e)
{
    // 构造Files文件夹的绝对路径,用Path.Combine避免跨平台斜杠兼容问题
    string filesDir = Path.Combine(Environment.CurrentDirectory, "Files");
    // 筛选目录下所有后缀为exe的文件,仅搜索顶层目录不遍历子文件夹
    string[] exeFiles = Directory.GetFiles(filesDir, "*.exe", SearchOption.TopDirectoryOnly);
    
    foreach (string exePath in exeFiles)
    {
        Process process = new Process()
        {
            StartInfo = new ProcessStartInfo(exePath)
            {
                WindowStyle = ProcessWindowStyle.Normal,
                WorkingDirectory = filesDir
            }
        };
        process.Start();
    }
}

补充说明:

  • 该写法同时兼容单个/多个exe的启动需求,哪怕后续Files目录下新增其他exe也会被全部启动
  • 直接复用提前构造的filesDir作为工作目录,比重复调用路径解析方法效率更高、出错概率更低
  • 如果需要处理无匹配exe的场景,可额外添加exeFiles.Length == 0的判断,自行补充提示逻辑即可

内容的提问来源于stack exchange,提问作者Sjdjidfkffnrkdlmf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 01:36:03