繁体   English   中英

cmd.exe进程永远不会完成

[英]cmd.exe process never completes

我有以下代码。

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";

执行到达“ string consoleOutput”,但从未到达“ string dir”,即代码在读取StandardOutput时卡住了。 如果有任何区别,可以从控制台应用程序中运行它。

您必须通过关闭流来显式完成对标准输入的写入。 请参阅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在评论中所建议)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM