StreamReader, C#, peek

牧云@^-^@ 提交于 2019-12-06 12:07:00

问题


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;
}  

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/1737591/streamreader-c-peek

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