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:
Sys开发者_运维知识库tem.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?
You're calling ReadToEnd
which will obviously block until the process terminates. You can repeatedly call Read
or ReadLine
instead. However, you should consider either doing this in a different thread or using events such as OutputDataReceived
to do this. (If you're using events, you need to call BeginOutputReadLine
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.
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:
void StartProcess()
{
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();
proc.OutputDataReceived += HandleExeOutput;
proc.BeginOutputReadLine();
}
private void HandleExeOutput(object sender, DataReceivedEventArgs e)
{
string output = e.Data;
// do something here with the string output
}
精彩评论