博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Fast Binary File Reading with C#

Posted on 2011-11-01 01:05  freewzx2005  阅读(576)  评论(0编辑  收藏  举报
public static TestStruct FromFileStream(FileStream fs) {     //Create Buffer      byte[] buff = new byte[Marshal.SizeOf(typeof(TestStruct))];      int amt = 0;      //Loop until we've read enough bytes (usually once)       while(amt < buff.Length)         amt += fs.Read(buff, amt, buff.Length-amt); //Read bytes       //Make sure that the Garbage Collector doesn't move our buffer       GCHandle handle = GCHandle.Alloc(buff, GCHandleType.Pinned);     //Marshal the bytes      TestStruct s =        (TestStruct)Marshal.PtrToStructure(handle.AddrOfPinnedObject(),        typeof(TestStruct));      handle.Free();//Give control of the buffer back to the GC       return s }
public static TestStruct FromBinaryReaderBlock(BinaryReader br) {     //Read byte array      byte[] buff = br.ReadBytes(Marshal.SizeOf(typeof(TestStruct)));     //Make sure that the Garbage Collector doesn't move our buffer       GCHandle handle = GCHandle.Alloc(buff, GCHandleType.Pinned);     //Marshal the bytes      TestStruct s =        (TestStruct)Marshal.PtrToStructure(handle.AddrOfPinnedObject(),       typeof(TestStruct));     handle.Free();//Give control of the buffer back to the GC       return s; }
public static TestStruct FromBinaryReaderField(BinaryReader br) {      TestStruct s = new TestStruct();//New struct       s.longField = br.ReadInt64();//Fill the first field       s.byteField = br.ReadByte();//Fill the second field       s.byteArrayField = br.ReadBytes(16);//...       s.floatField = br.ReadSingle();//...       return s; }