当 BinaryReader 打开时使用 Stream.Seek 是否安全?
- 作者: 八卦八股
- 来源: 51数据库
- 2023-02-13
问题描述
由于 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.
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源