开发者

weird behaviour of seek C#

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

Tha开发者_如何学编程nks,


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜