Seek C# 的奇怪行为
我在使用流时遇到一些困难。我正在使用 FileStream 和 BinaryReader,但出现了一些奇怪的行为。首先(这是另一个问题,当使用 StreamReader 时,我得到了奇怪的行为,当我执行 Peek 时,psoition 发生了更改,所以我使用了 BinaryReader,这很好)现在我遇到一个问题,有时当我执行 Seek 时(使用当然底层基本流 - FileStream)有时它工作正常(到达正确的位置),但有时它只是跳转到远远超出文件长度的位置,它不会一直发生,例如我遇到了问题到达1233*267的位置,但是一天后就正常了,问题出在另一个地方。
FileStream m_fsReader = new FileStream(m_strDataFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader m_brReader = new BinaryReader(m_fsReader);
和寻求部分:
m_fsReader.Seek(offset, SeekOrigin.Begin);
谢谢,
I have some difficulties with stream. I am using FileStream and BinaryReader and I got some weird behaviours. First of all (and this was on another question, when used StreamReader I got weird behaviour that when I did Peek the psoition was changed, so I used BinaryReader which was fine) NOW I have a problem that sometimes when I do Seek (using of course the underlying base stream - FileStream) SOMETIMES it works fine (get to the right position) but sometimes it just jumps to a position that is way beyond the file's length, It doesn't happen all the time, for instance I had a problem to get to a position at 1233*267, but a day later it was fine and the problem was at another place.
FileStream m_fsReader = new FileStream(m_strDataFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader m_brReader = new BinaryReader(m_fsReader);
and the seek part:
m_fsReader.Seek(offset, SeekOrigin.Begin);
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我注意到每个 Stream 都有自己的位置。当一个 Stream 由另一个 Stream 构造而成时,位置最初是相同的;但如果第二个流进行查找,它不会同步其基本流位置。
尝试在读取和查找操作后观察两个流的 Position 属性。您将看到操作和基本流位置值之间的差异。
在子流完成工作后,我通过在基本流上调用自己的 Seek 解决了这个问题。
I've noticed that every Stream keep its own position. When a Stream is constructed from another stream, the position is initially the same; but if the second stream seek, it doesn't synchronize its base stream position.
Try to watch Position property of both streams after read and seek operation. You will see discrepancies between the operation and the base stream Position value.
I solved this problem by calling myself Seek on the base stream after the work done by a substream.
这很难说,但我很确定,如果有一天工作另一天,文件不太可能被更改。
关于搜索方法,它允许您搜索超出流长度的任何位置。
来自 MSDN:
您可以寻找超出流长度的任何位置。当您搜索超出文件长度时,文件大小会增加。
http://msdn.microsoft.com/en-us/library/system.io.filestream.seek.aspx
It is difficult to say but I'm quite sure that is if one day work and another it does not probability the file has been changed.
Regarding the Seek Method it allow you to seek to any location beyond the length of the stream.
From MSDN:
You can seek to any location beyond the length of the stream. When you seek beyond the length of the file, the file size grows.
http://msdn.microsoft.com/en-us/library/system.io.filestream.seek.aspx