【问题标题】:Stuck while trying to run "cmd.exe /c SYSTEMINFO" in C#尝试在 C# 中运行“cmd.exe /c SYSTEMINFO”时卡住
【发布时间】:2014-08-19 16:36:55
【问题描述】:

我正在尝试在我的 C# WPF 应用程序中运行以下代码。每当我使用 dir 之类的东西时(我可能应该提到输出是我在 Visual Studio 中的工作文件夹的目录,而不是 System32),它允许它。但是,如果我使用 systeminfo 或将工作目录设置为 C:\Windows\System32,它就会挂起......

        MessageBox.Show("STARTED");

        var processInfo = new ProcessStartInfo("cmd.exe", "/c systeminfo") {
            CreateNoWindow = true,
            UseShellExecute = false,
            RedirectStandardError = true,
            RedirectStandardOutput = true,
            //WorkingDirectory = @"C:\Windows\System32\"
        };

        // *** Redirect the output ***
        Process process = Process.Start(processInfo);

        if (process == null) return false;
        process.WaitForExit();
        MessageBox.Show("Done");

        string output = process.StandardOutput.ReadToEnd().ToLower();
        string error = process.StandardError.ReadToEnd();
        int exitCode = process.ExitCode;
        MessageBox.Show(output);
        MessageBox.Show(error);
        MessageBox.Show(exitCode.ToString(CultureInfo.InvariantCulture));

有什么想法吗?

【问题讨论】:

  • 试试ProcessStartInfo("cmd.exe", "/c \"systeminfo\"")
  • 如果将CreateNoWindow 设置为false(因此它会显示命令提示符窗口)并运行它会发生什么?它是否显示任何消息?
  • @dr_andonuts 没用。 :(
  • 你意识到如果你重定向输出,你必须读取输出,对吧?如果你不这样做,它将填充管道的缓冲区并暂停线程试图打印出一些东西。
  • @Amorphous:不,不像你更新的代码。您必须在等待进程退出之前阅读它。如果您等待进程退出并且打印太多,它将挂起并且永远不会退出,您仍然不会读取输出来取消挂起它。

标签: c# .net wpf process cmd


【解决方案1】:

刚刚尝试过,并且按预期工作。
当然,您需要在进程关闭之前读取重定向的输出。

var processInfo = new ProcessStartInfo("cmd.exe", "/c systeminfo") 
{
    CreateNoWindow = true,
    UseShellExecute = false,
    RedirectStandardError = true,
    RedirectStandardOutput = true,
    WorkingDirectory = @"C:\Windows\System32\"
};

StringBuilder sb = new StringBuilder();
Process p = Process.Start(processInfo);
p.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data);
p.BeginOutputReadLine();
p.WaitForExit();
Console.WriteLine(sb.ToString());

【讨论】:

  • 你为什么要开始 p 两次?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-22
  • 2013-06-12
  • 2015-04-11
  • 2019-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多