Where to use StreamReader.DiscardBufferedData()? [

2019-09-27 10:24发布

问题:

I have the following code:

StreamReader StreamReader = new StreamReader("File.txt");
string Line = "";

while((Line = StreamReader.ReadLine()) != null)
{
    string Value = Line.Trim();
    string Value2 = StreamReader.ReadLine();
    int CursorValue = StreamReader.BaseStream.Position;

    if(Condition)
    {
        StreamReader.BaseStream.Position = SOMETHING_ELSE;
        Console.WriteLine(StreamReader.ReadLine());
    }

    StreamReader.BaseStream.Position = CursorValue;
}

Can anybody tell me where I am supposed to use StreamReader.DiscardBufferedData() here?

回答1:

From MSDN:

Use the DiscardBufferedData method to reset the internal buffer for the StreamReader object. You need to call this method only when the position of the internal buffer and the BaseStream do not match.

So a little example:

Stream s = new MemoryStream();
StreamReader sr = new StreamReader(s);
// Read things here.
s.Position = 10;
sr.DiscardBufferedData();        // reader now reading from position 0
sr.BaseStream.Seek(10, SeekOrigin.Begin); // Reader now reading from location 10.

In your case:

StreamReader.BaseStream.Position = SOMETHING_ELSE;
sr.DiscardBufferedData();
StreamReader.BaseStream.Seek(SOMETHING_ELSE, SeekOrigin.Begin);
Console.WriteLine(StreamReader.ReadLine());

and dont forget to set back again at:

StreamReader.BaseStream.Position = CursorValue;
sr.DiscardBufferedData();
StreamReader.BaseStream.Seek(CursorValue, SeekOrigin.Begin);


回答2:

MSDN

Use the DiscardBufferedData method to reset the internal buffer for the StreamReader object. You need to call this method only when the position of the internal buffer and the BaseStream do not match. These positions can become mismatched when you read data into the buffer and then seek a new position in the underlying stream. This method slows performance and should be used only when absolutely necessary, such as when you want to read a portion of the contents of a StreamReader object more than once. For a list of common I/O tasks, see Common I/O Tasks.