Mai*_*sad 1 .net c# cmd process
我正在尝试使用 C# 读取 Windows 电脑上的所有系统信息。这是我的代码:
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();
}
Run Code Online (Sandbox Code Playgroud)
但它只是打开一个控制台,不执行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;
}
Run Code Online (Sandbox Code Playgroud)
根据MSDN,您应该在调用之前设置RedirectStandardOutput为true并读取输出WaitForExit,否则可能会出现死锁
p.StandardOutput.ReadToEnd该示例通过调用before避免了死锁情况p.WaitForExit。p.WaitForExit如果父进程之前 调用p.StandardOutput.ReadToEnd并且子进程写入足够的文本来填充重定向流,则可能会导致死锁情况。父进程将无限期地等待子进程退出。
/c表示执行后终止命令行
| 归档时间: |
|
| 查看次数: |
4391 次 |
| 最近记录: |