我有以下代码片段,用于读取二进制文件并进行验证:
FileStream f = File.OpenRead("File.bin");
MemoryStream memStream = new MemoryStream();
memStream.SetLength(f.Length);
f.Read(memStream.GetBuffer(), 0, (int)f.Length);
f.Seek(0, SeekOrigin.Begin);
var r = new BinaryReader(f);
Single prevVal=0;
do
{
r.ReadUInt32();
var val = r.ReadSingle();
if (prevVal!=0) {
var diff = Math.Abs(val - prevVal) / prevVal;
if (diff > 0.25)
Console.WriteLine("Bad!");
}
prevVal = val;
}
while (f.Position < f.Length);
很不幸,它的工作速度非常慢,我正在寻求改进。在C++中,我会将文件读入字节数组,然后将该数组重新转换为结构体数组:
struct S{
int a;
float b;
}
我怎样用C#实现这个?