Process.Start 找不到指定的文件,但它肯定存在 - 为什么?

Process.Start can not find file specified, but it is definitely there - why?

我正在尝试 运行 来自 C# 的 DJOIN 命令。 (它默认存在于 Win 10 的 c:\windows\system32 目录中。)

当我运行以下内容时:

ProcessStartInfo psi = new ProcessStartInfo();
psi.UseShellExecute = false;
psi.FileName = @"c:\windows\system32\djoin.exe";
psi.RedirectStandardOutput = true;
psi.Arguments = "/C toast";
using (Process proc = Process.Start(psi))
{
using (StreamReader reader = proc.StandardOutput)
{
   string result = reader.ReadToEnd();
   MessageBox.Show(result);
}

我得到一个 "file not found" 错误:

An unhandled exception of type 'System.ComponentModel.Win32Exception' occurred in System.dll    
Additional information: The system cannot find the file specified

但是,如果我使用另一个 "out of the box" .exe,例如 "tasklist.exe",它工作正常。例如:

proc.StartInfo.FileName = "tasklist.exe";

给我以下输出:

原来问题是 DJOIN.exe 是 64 位的。我的应用程序是 运行 32 位的,所以我将平台更改为 X64 并且它可以正常工作。

参见:Start process as 64 bit

您还可以禁用 64 位文件夹重定向 OS

[System.Runtime.InteropServices.DllImport("Kernel32.Dll", EntryPoint = "Wow64EnableWow64FsRedirection")]
public static extern bool EnableWow64FSRedirection(bool enable);


        EnableWow64FSRedirection(false);

        try
        {
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.UseShellExecute = false;
            psi.FileName = @"c:\windows\system32\djoin.exe";
            psi.RedirectStandardOutput = true;
            psi.Arguments = " /C toast ";
            using (Process proc = Process.Start(psi))
            {
                using (System.IO.StreamReader reader = proc.StandardOutput)
                {
                    string result = reader.ReadToEnd();
                    MessageBox.Show(result);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        EnableWow64FSRedirection(true);

尝试 运行 cmd 命令,其中您的应用程序是一个参数。 以下对我有用:

ProcessStartInfo processInfo = new ProcessStartInfo("cmd", @"djoin.exe /C toast");

processInfo.RedirectStandardOutput = true;
processInfo.UseShellExecute = false;

Process ProcessObj = new Process();
ProcessObj.StartInfo = processInfo;

ProcessObj.Start();