How to read standard output line by line?

John Ryann picture John Ryann · Jan 9, 2014 · Viewed 19k times · Source

I want to inspect line by line standard output from process. after reading the second line myProcess.StandardOutput.EndofStream change from false to true. Hence it quits from while loop. Maybe I should use something else?

Process myProcess = new Process();
try
{
    myProcess.StartInfo.UseShellExecute = false;
    myProcess.StartInfo.FileName = my_command;
    myProcess.StartInfo.Arguments = " "+ location;
    myProcess.StartInfo.CreateNoWindow = true;
    myProcess.StartInfo.RedirectStandardOutput = true;
    myProcess.Start();

    while (!myProcess.StandardOutput.EndOfStream)
    {
        string standard_output = myProcess.StandardOutput.ReadLine();
        if (standard_output.Contains("xx"))
        {
           //do something

            break;
        }
    }

    myProcess.WaitForExit();
}

Answer

Mike Haboustak picture Mike Haboustak · Jan 9, 2014

Reading from StandardOutput isn't like reading from a file that has a definite endpoint. A StreamReader hooked to StandardOutput can reach EndOfStream (meaning all available output has been read) before the process exits.

ReadLine however, will wait until data is available or the stream is closed. When the stream is closed, ReadLine will return null.

Rewriting your main loop to use the blocking I/O of ReadLine as the wait condition:

    string standard_output;
    while ((standard_output = myProcess.StandardOutput.ReadLine()) != null) 
    {
        if (standard_output.Contains("xx"))
        {
            //do something
            break;
        }
    }