Process.start useshellexecute = false 时找不到文件

Process.start does not find file when useshellexecute = false

我需要从我的 UWP 应用程序调用批处理文件。方法似乎是 Process.Start(),但它说当我按照它输出的路径时,它甚至找不到文件,它确实存在。 当使用 shellexecute = false 时,文件路径和工作目录都作为完整路径给出。

当我设置 useshellexecute = true 时它起作用了。由于完整路径在这里有效,因此文件显然在那里。 使用 shellexecute = true 时,工作目录只指定它应该在哪里搜索文件,命令提示符从 system32 目录开始,但我需要工作目录是打开的批处理所在的位置。

因此 ShellExecute = false。

我试过: 1. ShellExecute = true。它找到了文件,但工作目录设置不正确。 2. 硬编码批处理的绝对路径。还是没找到。 3.设置StartInfo.FileName而不是通过参数给它。 4.相对路径 5. Process.Start(文件名)。没有 StartInfo 无法设置工作目录 6. 看看类似的问题,但答案总是我已有的(当shellexecute = false时使用完整路径)

string executable = args[2];

string path = Assembly.GetExecutingAssembly().CodeBase;
string directory = Path.GetDirectoryName(path);

var startInfo = new ProcessStartInfo(directory + @"\Diagnose\_data\Updater\" + executable);

startInfo.UseShellExecute = false;
startInfo.WorkingDirectory = directory + @"\Diagnose\_data\Updater";

startInfo.RedirectStandardError = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;

Process.Start(startInfo);

它应该找到文件,因为给出了完整的绝对路径并且文件确实存在,但它给出了找不到文件的错误。

使用Assembly.Location instead of Application.CodeBaseApplication.CodeBase returns 程序集的源位置作为 URL,而不是文件路径。程序集可以从 URL 或字节数组加载,CodeBase 反映了这一点。它 returns 类似于 :

file:///C:/TEMP/LINQPad6/_kighplqc/neuyub/LINQPadQuery.dll

Windows shell 可以处理文件 URL 并将它们转换为实际文件路径。 OS 本身需要文件路径。

您也应该使用 Path.Combine 而不是连接字符串,以避免出现多余或缺少斜线的问题。你应该使用类似的东西:

string path = Assembly.GetExecutingAssembly().Location;
string directory = Path.GetDirectoryName(path);
var execPath=Path.Combine(directory,"Diagnose\_data\Updater",executable);

var startInfo = new ProcessStartInfo(execPath);