我有一个小型控制台应用程序,我想读取C#中的输出。因此,我创建了这个代码片段。命令提示符将打开,但不会显示任何内容。
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
process.StartInfo.FileName = DirectoryPath + "Test.exe";
process.StartInfo.Arguments = "-showAll";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
process.WaitForExit(2000);
String strOutput = process.StandardOutput.ReadToEnd();如果删除UseShellExecute、RedirectStandardOutput和最后一行,则会打开命令提示符并显示Test.exe,但需要将输出作为字符串,因此必须使用以下属性来读取StandardOutput
我还尝试将超时设置为2秒(process.WaitForExit(2000)),但空命令提示符在2秒后不会关闭。
如果在调试模式下手动关闭空命令提示符,变量strOutput将得到我所请求的信息。
发布于 2016-10-26 08:08:45
为了避免死锁,您必须在等待退出之前读取输出流。所以试着:
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
process.StartInfo.FileName = DirectoryPath + "Test.exe";
process.StartInfo.Arguments = "-showAll";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
String strOutput = process.StandardOutput.ReadToEnd();
process.WaitForExit();https://stackoverflow.com/questions/40256736
复制相似问题