【问题标题】:How can I run an exe file with c# (I can't use Process.Start() because I don't know the exe file's location)如何使用 c# 运行 exe 文件(我不能使用 Process.Start() 因为我不知道 exe 文件的位置)
【发布时间】:2020-12-24 11:30:20
【问题描述】:

我想用 c# 运行一个 exe 文件,但我不能使用 Process.Start(),因为我不知道 exe 文件的位置。

我还没有开始写,所以我暂时没有任何代码。

【问题讨论】:

  • "因为我现在不知道 exe 文件的方向。" -- 这里的“方向”是什么意思? Process.Start 从 C# 运行 exe 的方式
  • 我的意思是“位置”,exe文件的路径
  • 你想运行一个文件,但你不知道文件在哪里?你怎么知道文件存在?这显然是做不到的。
  • 如果文件存在于您的PATH中,只需将exe名称提供给Proess.Start,它就会搜索您的PATH以找到该exe。
  • 您至少知道 exe 的名称吗?如果是正在运行的进程,可以找到manually(shell)

标签: c# process.start


【解决方案1】:

使用以下:

            string locateFile = "cmd.exe";
            string environPath = Environment.GetEnvironmentVariable("Path");
            string[] paths = environPath.Split(new char[] { ';' }).ToArray();

            string filePath = "";
            foreach (string path in paths)
            {
                string file = Directory.GetFiles(path, locateFile, SearchOption.TopDirectoryOnly).FirstOrDefault();
                if (file != null)
                {
                    filePath = file;
                    break;
                }
            }
            if (filePath.Length > 0)
            {
                Console.WriteLine("File location : '{0}'", filePath);
            }
            else
            {
                Console.WriteLine("File not found");
            }
            Console.ReadLine();

【讨论】:

  • 没必要这么费劲,确定吗? Process.Start 已搜索 PATH
  • @canton7 : 进程类没有环境变量。如果您设置了 Process Path 变量并且找不到该文件,那么您必须处理异常。
  • 我不确定你想说什么。例如,Process.Start("cmd.exe") 工作正常。是的,如果你的 PATH 中不存在 exe,你会得到一个异常,但这很好
  • @canton7 :我以前从未使用过这种重载。每次使用流程类时都会出现异常,解决方法是添加完整路径。
  • use ProcessStartInfo 得到的结果完全一样
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-25
  • 1970-01-01
  • 2014-03-26
  • 1970-01-01
  • 1970-01-01
  • 2012-03-29
  • 1970-01-01
相关资源
最近更新 更多