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?
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;
}
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With