2013-01-31 32 views
0

我有以下代码。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"; 

执行到达“字符串consoleOutput”,但从来没有达到“字符串目录”,即代码卡上读取StandardOutput。它在控制台应用程序中运行,如果这有所作为。

+2

如果您已经从控制台应用程序运行,为什么不直接调用'ipconfig'而不是不必要地产生'cmd'? – Petesh

+0

我可以用console.write来做这个吗? – coolblue2000

+0

console.write实际上不会启动该进程,它是启动它的'Process.Start(si)'。 – Petesh

回答

1

您必须通过关闭流来显式完成写入标准输入。请参阅Microsoft's example

总结:

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

编辑:测试在Visual Studio。

顺便说,要使用WriteLine()而不是Write()

+0

完美地工作,谢谢 – coolblue2000

0

使用WriteLine而不是Write来写一个带有最终换行符的字符串。 (您可能还需要拨打Flush(),但我不确定)。正如另一个答案所说,它不会对Close流造成伤害。

是的,你不需要cmd.exe,你可以直接启动ipconfig(由@Petesh在评论建议)。

+0

'Flush()'和'FlushAsync()'似乎没有出于某种原因。不知道为什么。 – Jason