打开BinaryReader时使用Stream.Seek安全吗? [英] Is it safe to use Stream.Seek when a BinaryReader is open?

查看:74
本文介绍了打开BinaryReader时使用Stream.Seek安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于BinaryReader的幕后缓冲策略,我不清楚是否可以读取存储在流中的偏移量,然后将流重新定位在该偏移量以恢复流传输.

Because of the under the hood buffering strategy of BinaryReader, it is unclear to me whether is it ok or not to read an offset stored in a stream, then reposition the stream at this offset to resume the streaming.

作为示例,可以使用以下代码:

As an example, is the following code ok:

using (var reader = new CustomBinaryReader(inputStream))
{
   var offset= reader.ReadInt32();
   reader.BaseStream.Seek(offset, SeekOrigin.Begin);

   //Then resume reading the streaming
}

还是我应该在寻找流之前关闭第一个二进制阅读器,然后重新打开第二个阅读器?

Or should I close the first binary reader before Seeking the stream and then reopen a second reader ?

int offset;
using (var firstReader = new CustomBinaryReader(inputStream))
{
   offset= firstReader.ReadInt32();
}
inputStream.Seek(offset, SeekOrigin.Begin);
using (var secondReader = new CustomBinaryReader(inputStream))
{
   //Then resume reading the streaming
}

推荐答案

BinaryReader确实使用了缓冲区,但仅 可以从基本流中读取足够的字节以转换值.换句话说,ReadInt32()将首先缓冲4个字节,ReadDecimal()将首先缓冲16个字节,依此类推.ReadString()是一个比较棘手的方法,但是它也有对策,BinaryWriter会在文件中对字符串进行编码,然后首先写入字符串长度.这样BinaryReader会在转换字符串之前确切知道要缓冲多少字节.

BinaryReader does use a buffer but only to read enough bytes from the base stream to convert a value. In other words, ReadInt32() will buffer 4 bytes first, ReadDecimal() will buffer 16 bytes first, etcetera. ReadString() is the trickier method but it has counter-measures as well, a string is encoded in the file by BinaryWriter which writes the string length first. So that BinaryReader knows exactly how many bytes to buffer before converting the string.

因此,在ReadXxx()方法之一返回并且在BaseStream上调用Seek()以后,缓冲区始终为空.也是Microsoft不需要覆盖Seek()方法的原因.

So the buffer is always empty after one of the ReadXxx() method returns and calling Seek() on the BaseStream is fine. Also the reason that Microsoft didn't need to override the Seek() method.

MSDN文章中的警告提示是适当的,如果在Seek()调用之后调用ReadXxx()方法,您肯定会多次读取偏移"值.但是我认为那完全是故意的.

The cautionary note in the MSDN article is appropriate, you certainly will read that "offset" value more than once if you call a ReadXxx() method after the Seek() call. I however assume that was entirely intentional.

这篇关于打开BinaryReader时使用Stream.Seek安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆