且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何逐行读取标准输出线?

更新时间:2023-11-17 23:53:22

这StandardOutput读数不像从具有明确的端点的文件中读取。钩住StandardOutput一个StreamReader可以达到EndOfStream在进程退出之前(即所有可用的输出被读取)。



不过的ReadLine,会等到数据可用,或流被关闭。当流被关闭,的ReadLine将返回null



重写你的主循环中使用的阻断我的ReadLine / O的作为等待条件:

 字符串standard_output; 
,而((standard_output = myProcess.StandardOutput.ReadLine())!= NULL)
{
如果(standard_output.Contains(XX))
{
//做些什么
中断;
}
}


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

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