【问题标题】:Process.start does not find file when useshellexecute = false当 useshellexecute = false 时 Process.start 找不到文件
【发布时间】:2019-11-09 06:17:35
【问题描述】:

我需要从我的 UWP 应用程序中调用批处理文件。这样做的方法似乎是 Process.Start(),但它说它没有找到文件,即使它很困难,当我按照它输出的路径时它肯定在那里。 当使用 shellexecute = false 时,文件路径和工作目录都以完整路径的形式给出。

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

因此 ShellExecute = false。

我试过了: 1. ShellExecute = 真。它找到了文件,但工作目录设置不正确。 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);

它应该找到该文件,因为给出了一个完整的绝对路径,并且该文件肯定在那里,但它给出了一个找不到文件的错误。

【问题讨论】:

    标签: c# uwp processstartinfo start-process


    【解决方案1】:

    使用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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-05
      • 2019-05-14
      相关资源
      最近更新 更多