Where to use StreamReader.DiscardBufferedData()? [closed]

二次信任 提交于 2019-12-13 23:17:14

问题


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.



来源:https://stackoverflow.com/questions/21163162/where-to-use-streamreader-discardbuffereddata

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!