Is it safe to use Stream.Seek when a BinaryReader is open?(当 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() 没问题.也是微软不需要重写 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 是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当 BinaryReader 打开时使用 Stream.Seek 是否安全?
基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- c# Math.Sqrt 实现 2022-01-01