简体   繁体   中英

StreamReader, C#, peek

I have a StreamReader that once in a while check if it has more to read from a simple text file. It uses peek property. The problem is that when I am using peek the position is changed, althougth not suppose to.

FileStream m_fsReader = new FileStream(
                        m_strDataFileName,
                        FileMode.OpenOrCreate,
                        FileAccess.Read,
                        FileShare.ReadWrite                        );

StreamReader m_SR = new StreamReader(m_fsReader);

Console.WriteLine("IfCanRead SR Position " + m_fsReader.Position +
     " and Length " + m_fsReader.Length);

if (m_SR.Peek() == -1) {
       Console.WriteLine("IfCanRead false 2 SR Position " + 
             m_fsReader.Position  + " and Length " + m_fsReader.Length);

       return false;
}
else {
       Console.WriteLine("IfCanRead true 2 SR Position " + 
           m_fsReader.Position + " and Length " + m_fsReader.Length);

       return true;
}  

The documentation indicates that the position of the StreamReader is not changed, but you are checking the underlying stream's current position, not that of the reader itself. I don't see that it guarantees that the position of the underlying stream remains the same. In fact, I suspect that it simply reads it and buffers internally to keep the reader's cursor at the previous position. This would mean that it doesn't guarantee that the underlying stream's position is unchanged.

The current position of the StreamReader object is not changed by Peek. The returned value is -1 if no more characters are currently available.

Tested this out myself. Position of the underlying FileStream has changed, but the key point is, that doesn't mean that the StreamReader has actually CONSUMED any bytes. So there is no problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM