我正在使用 BinaryWriter 将数据写入日志文件。
但是,当我使用 BinaryReader 检索数据(在循环内)时,我能够读取前 3 次写入(整数、整数、字节 []),但循环中的下一次迭代读取另外 3 似乎只是抓住了其余数据(我无法处理)。
这是代码:
编写代码:
writer.Write(header.StructID);
writer.Write(data.Length);
writer.Write(data);
阅读代码:
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (BinaryReader br = new BinaryReader(fs))
{
long bytesRead = 0;
long readerLen = br.BaseStream.Length;
//read 1st record
int id = br.ReadInt32();
int len = br.ReadInt32();
byte[] data = br.ReadBytes(len);
bytesRead += (sizeof(int) * 2) + data.Length;
while (bytesRead < readerLen)
{
//TODO:process data
//read next
id = br.ReadInt32();
len = br.ReadInt32();
data = br.ReadBytes(len);
bytesRead += (sizeof(int) * 2) + data.Length;
}
}
}
感谢您帮助解决!
编辑:
我将二进制写入代码包含在 using 语句中,并且只允许它执行 1 次,因此我确切地知道写入了多少字节。当我处理读取的代码时,basestream.length 更大(即我写了 80 个字节,basestream.length 显示为 1144)。
using (writer = new BinaryWriter(File.Open(filename, FileMode.OpenOrCreate)))
{
long pos = writer.BaseStream.Position;
writer.Write(header.StructID);
writer.Write(data.Length);
writer.Write(data);
m_LoggingEnabled = false;
}
这是二进制数据:
CE 00 00 00 48 00 00 00 AD A2 3B 94 76 08 A7 3E 7A 9A 80 9D CC 1A 2B 3F 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 F0 BF 91 01 00 00 00 00 00 00 00 00 00 00 00 00 F0 3F 01 00 00 00 00 00 00 00 CE 00 00 00 48 00 00 00 AD A2 3B 94 76 08 A7 3E 7A 9A 80 9D CC 1A 2B 3F 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 F0 BF 92 01 00 00 00 00 00 00 00 00 00 00 00 2A 7A BE 01 00 00 00 50 64 63 3D CE 00 00 00 48 00 00 00 D8 41 B1 19 01 A3 86 BE E2 E2 7A 22 6F 1F 2B 3F 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 F0 BF 91 01 00 00 00 00 00 00 00 00 00 00 00 00 F0 3F 01 00 00 00 00 00 00 00
我现在真的很困惑!