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

时间:2019-06-27 08:54:57

标签: c# uwp processstartinfo start-process

我需要从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);

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

1 个答案:

答案 0 :(得分:2)

使用Assembly.Location代替Application.CodeBaseApplication.CodeBase以URL而不是文件路径的形式返回程序集的源位置。可以从URL或字节数组加载程序集,CodeBase反映了这一点。它返回类似:

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

Windows Shell可以处理文件URL并将其转换为实际的文件路径。操作系统本身需要文件路径。

您也应该使用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);