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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With