问题
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?
回答1:
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;
}
}
回答2:
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.
回答3:
There is no reliable way to move reading location backward in text readers. You can try to seek underlying stream but it may not be possible (if stream does not supprt seek) or may not give results you want if any kind of caching happens inside reader.
The most realiable approach would be to remember the last line, you may consider creating custom class that will extend reader with PeekString functionality... But it may be hard to implement properly if you will need to re-read that string using other reader methods.
回答4:
You can read all the lines from the file (ReadAllLines), then you can easily operate on them. But look at the size of the file, that you could use too much memory.
来源:https://stackoverflow.com/questions/13548443/textreader-and-peek-next-line