Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextReader and peek next line

Tags:

c#

.net

.net-4.0

I read a data from a text file using TextReader

TextReader reader = new StreamReader(stream);
string line;
while ((line = reader.ReadLine()) != null)
 {
   //.......
 }

Sometimes I need to peek next line (or a few next lines) from reader.

How do I do that?

like image 519
Alan Coromano Avatar asked Dec 26 '22 14:12

Alan Coromano


2 Answers

EDIT: Updated to allow any number of peeks:

public class PeekingStreamReader : StreamReader
{
    private Queue<string> _peeks;

    public PeekingStreamReader(Stream stream) : base(stream)
    {
        _peeks = new Queue<string>();   
    }

    public override string ReadLine()
    {
        if (_peeks.Count > 0)
        {
            var nextLine = _peeks.Dequeue();
            return nextLine;
        }
        return base.ReadLine();
    }

    public string PeekReadLine()
    {
        var nextLine = ReadLine();
        _peeks.Enqueue(nextLine);
        return nextLine;
    }
}
like image 174
armen.shimoon Avatar answered Dec 29 '22 02:12

armen.shimoon


You need to do this yourself; however, it is not that difficult:

public class PeekTextReader {
    string lastLine;
    private readonly TextReader reader;
    public PeekTextReader(TextReader reader) {
        this.reader = reader;
    }
    public string Peek() {
        return lastLine ?? (lastLine = reader.ReadLine());
    }
    public string ReadLine() {
        string res;
        if (lastLine != null) {
            res = lastLine;
            lastLine = null;
        } else {
            res = reader.ReadLine();
        }
        return res;
    }
}

Note that peeking once will keep the line locked in until you do a full ReadLine.

like image 21
Sergey Kalinichenko Avatar answered Dec 29 '22 03:12

Sergey Kalinichenko