简体   繁体   English

cmd.exe进程永远不会完成

[英]cmd.exe process never completes

I have the following code. 我有以下代码。

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

The execution reaches "string consoleOutput" but never reaches "string dir" ie the code gets stuck on reading the StandardOutput. 执行到达“ string consoleOutput”,但从未到达“ string dir”,即代码在读取StandardOutput时卡住了。 It is runnung from within a console application if this makes any difference. 如果有任何区别,可以从控制台应用程序中运行它。

You have to explicitly finish writing to the standard input by closing the stream. 您必须通过关闭流来显式完成对标准输入的写入。 See Microsoft's example . 请参阅Microsoft的示例

In summary: 综上所述:

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

Edit: Tested in Visual Studio. 编辑:在Visual Studio中测试。

By the way , you want to use WriteLine() instead of Write() . 顺便说一句 ,您想使用WriteLine()而不是Write()

Use WriteLine instead of Write to write a string with a final newline. 使用WriteLine而不是Write来写一个带有最后换行符的字符串。 (You might have to call Flush() as well, but I'm not sure). (您可能还必须调用Flush() ,但我不确定)。 It won't hurt to Close the stream, as another answer says. 另一个答案说, Close流不会有什么坏处。

And yes, you don't need cmd.exe , you can start ipconfig directly (as advised by @Petesh in a comment). 是的,您不需要cmd.exe ,可以直接启动ipconfig (如@Petesh在评论中所建议)。

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

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