Mega Code Archive

 
Categories / C# / File Stream
 

Read Struct out of a file with BinaryReader

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.InteropServices; public static class Helper {     public static T ReadStruct<T>(BinaryReader binary_reader) where T : struct     {         Byte[] buffer = new Byte[Marshal.SizeOf(typeof(T))];         binary_reader.Read(buffer, 0, buffer.Count());         GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);         T result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));         handle.Free();         return result;     } }