我正在尝试使用 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
beforep.WaitForExit
. A deadlock condition can result if the parent process callsp.WaitForExit
beforep.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/