cmd.exe进程永远不会完成



>我有以下代码。

ProcessStartInfo si = new ProcessStartInfo("cmd.exe");
si.RedirectStandardInput = true;
si.RedirectStandardOutput = true;
si.UseShellExecute = false;
si.WindowStyle = ProcessWindowStyle.Hidden;
si.CreateNoWindow = true;
Process p = Process.Start(si);
p.StandardInput.Write("ipconfig");
p.StandardInput.Write("exit");
string consoleOutput = p.StandardOutput.ReadToEnd();
string dir="here";
执行到达"字符串控制台输出",

但永远不会到达"字符串目录",即代码在读取标准输出时卡住。如果这有任何区别,则从控制台应用程序中运行它。

您必须通过关闭流来显式完成对标准输入的写入。请参阅Microsoft的示例。

总结:

        p.StandardInput.Write("exit");
        p.StandardInput.Close(); // <-- You need this
        string consoleOutput = p.StandardOutput.ReadToEnd();

编辑:在Visual Studio中测试。

顺便说一下,你想用WriteLine()而不是Write()

使用 WriteLine 而不是 Write 来编写带有最后一个换行符的字符串。(你可能也必须打电话给Flush(),但我不确定)。正如另一个答案所说,Close流不会有什么坏处。

是的,你不需要cmd.exe,你可以直接开始ipconfig(按照@Petesh在评论中的建议)。

最新更新