【问题标题】:BCDEDIT not recognized when running via C#通过 C# 运行时无法识别 BCDEDIT
【发布时间】:2012-12-10 23:26:08
【问题描述】:

当我尝试从我的 C# 应用程序运行 BCDEDIT 时,我收到以下错误:

'bcdedit' 未被识别为内部或外部 命令, 可运行的程序或批处理文件。

当我通过提升的命令行运行它时,我得到了预期的结果。

我使用了以下代码:

            Process p = new Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.FileName = @"CMD.EXE";
            p.StartInfo.Arguments = @"/C bcdedit";
            p.Start();
            string output = p.StandardOutput.ReadToEnd();
            String error = p.StandardError.ReadToEnd();
            p.WaitForExit();
            return output;

我也尝试过使用

p.StartInfo.FileName = @"BCDEDIT.EXE";
p.StartInfo.Arguments = @"";

我尝试了以下方法:

  1. 检查路径变量 - 它们没问题。
  2. 从提升的命令提示符运行 Visual Studio。
  3. 放置完整路径。

我的想法不多了, 关于我为什么会收到此错误的任何想法?

如果还有其他方法也可以,我需要的只是命令的输出。 谢谢

【问题讨论】:

  • 尝试将 bcdedit 放入您的 debug/bin 文件夹,看看是否可行。你也可以直接调用 BCDEDIT,你不必运行 cmd.exe
  • @Mataniko,谢谢 - 将它放在调试目录中似乎可行,但为什么在 system32 路径中找不到呢?
  • 这是路径设置,David Heffernan 的回答似乎是罪魁祸首。

标签: c# windows


【解决方案1】:

有一种解释是有道理的:

  1. 您正在 64 位机器上执行程序。
  2. 您的 C# 程序构建为 x86。
  3. bcdedit.exe 文件存在于C:\Windows\System32 中。
  4. 虽然C:\Windows\System32 在您的系统路径上,但在x86 进程中,您受制于File System Redirector。这意味着C:\Windows\System32 实际上解析为C:\Windows\SysWOW64
  5. C:\Windows\SysWOW64 中没有 32 位版本的 bcdedit.exe

解决方案是将您的 C# 程序更改为以 AnyCPUx64 为目标。

【讨论】:

  • 谢谢!!! , 你是对的。疯狂地想弄清楚。感谢您的帮助!
  • 另外值得注意的是,我在另一个 SO link 中看到使用 p.StartInfo.UseShellExecute = false; PATH 没有按预期使用。
  • 我认为这无关紧要。当为 wow64 重定向时,bcdedit.exe 不在路径中,这很简单。
【解决方案2】:

如果您在 32it/64 位 Windows 上都无法使用 x86 应用程序,并且您需要调用 bcdedit 命令,以下是一种方法:

private static int ExecuteBcdEdit(string arguments, out IList<string> output)
{
    var cmdFullFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows),
                                       Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess
                                           ? @"Sysnative\cmd.exe"
                                           : @"System32\cmd.exe");

    ProcessStartInfo psi = new ProcessStartInfo(cmdFullFileName, "/c bcdedit " + arguments) { UseShellExecute = false, RedirectStandardOutput = true };
    var process = new Process { StartInfo = psi };

    process.Start();
    StreamReader outputReader = process.StandardOutput;
    process.WaitForExit();
    output = outputReader.ReadToEnd().Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();
    return process.ExitCode;
}

用法:

var returnCode = ExecuteBcdEdit("/set IgnoreAllFailures", out outputForInvestigation);

灵感来自这个帖子,来自How to start a 64-bit process from a 32-bit processhttp://www.samlogic.net/articles/sysnative-folder-64-bit-windows.htm

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 2018-02-06
    • 2020-10-17
    • 1970-01-01
    相关资源
    最近更新 更多