C#, read structures from binary file
See the question and my original answer on StackOverflowHere is a slightly modified version of Jesper's code:
public static T? ReadStructure<T>(this Stream stream) where T : struct
{
if (stream == null)
return null;
int size = Marshal.SizeOf(typeof(T));
byte[] bytes = new byte[size];
if (stream.Read(bytes, 0, size) != size) // can't build this structure!
return null;
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try
{
return (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
}
finally
{
handle.Free();
}
}
It handles EOF cases successfully as it returns a nullable type.