How to read standard output line by line?

徘徊边缘 提交于 2020-01-10 02:54:18

问题


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();
}

回答1:


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;
        }
    }


来源:https://stackoverflow.com/questions/21027400/how-to-read-standard-output-line-by-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!