C# 执行、等待、读取命令的输出

标签 c# .net cmd process

我正在尝试使用 C# 读取 Windows PC 上的所有系统信息。这是我的代码:

 public static string GetSystemInfo()
        {
            String command = "systeminfo";
            ProcessStartInfo cmdsi = new ProcessStartInfo("cmd.exe");
            cmdsi.Arguments = command;
            Process cmd = Process.Start(cmdsi);
            cmd.WaitForExit();
            return cmd.StandardOutput.ReadToEnd();
        }

但它只是打开一个控制台,并不执行systeminfo命令。

如何解决这个问题?

最佳答案

下面的代码片段可以工作

public static string GetSystemInfo()
{
    var command = "/c systeminfo";
    var cmdsi = new ProcessStartInfo("cmd.exe");
    cmdsi.Arguments = command;
    cmdsi.RedirectStandardOutput = true;
    cmdsi.UseShellExecute = false;
    var cmd = Process.Start(cmdsi);
    var output = cmd.StandardOutput.ReadToEnd();

    cmd.WaitForExit();

    return output;
}

您应该将 RedirectStandardOutput 设置为 true 并在调用 WaitForExit 之前读取输出,否则您会遇到死锁,根据 MSDN

The example avoids a deadlock condition by calling p.StandardOutput.ReadToEnd before p.WaitForExit. A deadlock condition can result if the parent process calls p.WaitForExit before p.StandardOutput.ReadToEnd and the child process writes enough text to fill the redirected stream. The parent process would wait indefinitely for the child process to exit.

/c 表示执行完结束命令行

关于C# 执行、等待、读取命令的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59163297/

相关文章:

c# - 使此 C# SwapBytes 代码与 x64 兼容

c# - 有没有更好的方法来使用 LINQ 聚合字典?

c# - 与声明实例变量的方式不同

java - 如何让 ProcessBuilder 处理嵌套引号?

c# - 如何将 IFactory 绑定(bind)到具体实现?

.net - 如何在 CheckedListbox 中 CheckOnClick 但仅在复选框上方时?

.net - .Net @ VS 中使用 MySQL 准备的语句?

c# - 使用远程桌面的远程计算机的 MachineName

performance - 在Powershell脚本或命令行中创建和编辑性能计数器

java - 如何在cmd中使用java程序作为命令?