C# cmd.exe进程从未完成
我有以下代码C# cmd.exe进程从未完成,c#,.net,console,C#,.net,Console,我有以下代码 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.Sta
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";
执行达到“字符串控制台输出”,但从未达到“字符串目录”,即代码在读取标准输出时卡住。如果这有什么不同,它将在控制台应用程序中运行。您必须通过关闭流来明确地完成对标准输入的写入。看 总之:
p.StandardInput.Write("exit");
p.StandardInput.Close(); // <-- You need this
string consoleOutput = p.StandardOutput.ReadToEnd();
p.StandardInput.Write(“退出”);
p、 StandardInput.Close();// 使用WriteLine
而不是Write
来编写带有最后换行符的字符串。(您可能还需要调用Flush()
,但我不确定)。另一个答案是,关闭流不会有什么坏处
是的,您不需要cmd.exe
,您可以直接启动ipconfig
(正如@Petesh在评论中建议的那样)。如果您已经从控制台应用程序运行,你为什么不自己调用ipconfig
,而不是不必要地生成cmd
?我可以用console.write做这件事吗?console.write实际上不会启动进程,它是进程.Start(si)
启动它。我是从与正在运行的控制台应用程序在同一进程中执行命令的角度提出要求的。Flush()
和FlushAsync()
出于某种原因似乎没有这样做。不知道为什么。