我正在尝试使用C#读取二进制数据。我拥有关于我想要读取的文件中数据布局的所有信息。我能够读取数据“块大块”,即获得前40个字节的数据将其转换为字符串,获得接下来的40个字节。将二进制文件读入结构中
由于至少有三个稍微不同的版本的数据,我想直接读取数据到一个结构。它只是比“逐行阅读”更让人感觉正确。
我曾尝试以下方法,但都无济于事:
StructType aStruct;
int count = Marshal.SizeOf(typeof(StructType));
byte[] readBuffer = new byte[count];
BinaryReader reader = new BinaryReader(stream);
readBuffer = reader.ReadBytes(count);
GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned);
aStruct = (StructType) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(StructType));
handle.Free();
流是打开的FileStream从中我已经开始从阅读。当使用Marshal.PtrToStructure
时,我得到一个AccessViolationExceptio
n。
流包含的信息比我想要读取的更多,因为我对文件末尾的数据不感兴趣。
的结构的定义如下:
[StructLayout(LayoutKind.Explicit)]
struct StructType
{
[FieldOffset(0)]
public string FileDate;
[FieldOffset(8)]
public string FileTime;
[FieldOffset(16)]
public int Id1;
[FieldOffset(20)]
public string Id2;
}
的示例代码是从原始改变,使这一问题更短。
如何将二进制数据从文件读取到结构中?
BinaryFormatter有自己的二进制数据格式 - 如果您自己读取/写入数据,这很好。如果您从其他来源获取文件则无用。 – russau 2009-07-26 07:11:52