在c#中不断读取控制台流
我想在 C# 中读取 cmd 的连续输出流。我知道我可以重定向标准输出流并读取它。以下是代码:
System.Diagnostics.ProcessStartInfo pi= new System.Diagnostics.ProcessStartInfo(ProgramPATH,Params);
pi.RedirectStandardOutput = true;
pi.UseShellExecute = false;
pi.CreateNoWindow = true;
System.Diagnostics.Process proc= new System.Diagnostics.Process();
proc.StartInfo = pi;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
但这一次给出了整个输出。如果我发出带有 -t
参数的 ping
命令会怎么样?我如何才能持续阅读此流?
I want to read a continues output stream of cmd in c#. I know that I can redirect the standard output stream and read it. Following is the code:
System.Diagnostics.ProcessStartInfo pi= new System.Diagnostics.ProcessStartInfo(ProgramPATH,Params);
pi.RedirectStandardOutput = true;
pi.UseShellExecute = false;
pi.CreateNoWindow = true;
System.Diagnostics.Process proc= new System.Diagnostics.Process();
proc.StartInfo = pi;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
But this gives the whole output at once. What if I issue ping
command with -t
argument? How I can read this stream continually?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在调用
ReadToEnd
,这显然会阻塞,直到进程终止。您可以重复调用Read
或ReadLine
。但是,您应该考虑在不同的线程中执行此操作,或者使用诸如OutputDataReceived
来执行此操作。 (如果您使用事件,则需要调用 < code>BeginOutputReadLine 来启用事件 - 有关详细信息,请参阅 MSDN 示例。)可能在不同线程上读取的原因是,如果您需要从两个标准读取错误和标准输出,您需要确保进程不会填满其缓冲区 - 否则它可能会在写入时阻塞,从而有效地导致死锁。使用异步方法可以更轻松地处理此问题。
You're calling
ReadToEnd
which will obviously block until the process terminates. You can repeatedly callRead
orReadLine
instead. However, you should consider either doing this in a different thread or using events such asOutputDataReceived
to do this. (If you're using events, you need to callBeginOutputReadLine
to enable the events - see the MSDN examples for details.)The reason for potentially reading on a different thread is that if you need to read from both standard error and standard output, you need to make sure the process doesn't fill up its buffer - otherwise it could block when writing, effectively leading to deadlock. Using the asynchronous approach makes it simpler to handle this.
为了节省那些不想查看文档的人的时间,请参阅 StartProcess 和 HandleExeOutput 方法中的最后 2 行:
To save time for those who don't want to look at the docs, see the last 2 lines in StartProcess and the HandleExeOutput method: