Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading console stream continually in c#

Tags:

c#

process

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?

like image 822
Vinod Maurya Avatar asked Feb 18 '11 17:02

Vinod Maurya


1 Answers

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.

like image 61
Jon Skeet Avatar answered Sep 21 '22 23:09

Jon Skeet