简体   繁体   English

StreamReader,C#,偷看

[英]StreamReader, C#, peek

I have a StreamReader that once in a while check if it has more to read from a simple text file. 我有一个StreamReader,偶尔会检查是否有更多要从简单的文本文件中读取。 It uses peek property. 它使用peek属性。 The problem is that when I am using peek the position is changed, althougth not suppose to. 问题在于,当我使用peek时,位置会发生变化,而不是假设。

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. 文档表明StreamReader的位置没有改变,但是你正在检查底层流的当前位置,而不是读取器本身的位置。 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. Peek不会更改StreamReader对象的当前位置。 The returned value is -1 if no more characters are currently available. 如果当前没有更多字符可用,则返回值为-1。

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. 底层FileStream的位置已经改变,但关键是,这并不意味着StreamReader实际上已经消耗了任何字节。 So there is no problem. 所以没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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