using System; using System.IO; using System.Runtime.InteropServices; using Vanara.InteropServices; namespace Vanara.Extensions { /// Extensions for classes in System.IO. public static class IOExtensions { /// Writes the specified structure value of type into a binary stream. /// The type of the structure value to write. /// The instance to write into. /// The value to write. public static void Write(this BinaryWriter writer, T value) { if (value == null) return; if (!typeof(T).IsBlittable()) throw new ArgumentException(@"The type parameter layout is not sequential or explicit.", nameof(T)); var sz = Marshal.SizeOf(value); var bytes = new byte[sz]; using (var ptr = new PinnedObject(value)) Marshal.Copy(ptr, bytes, 0, sz); writer.Write(bytes); } /// Reads the specified structure value of type from a binary stream. /// The type of the structure value to read. /// The instance to read from. /// The value to read from the stream. public static T Read(this BinaryReader reader) { if (!typeof(T).IsBlittable()) throw new ArgumentException(@"The type parameter layout is not sequential or explicit.", nameof(T)); var sz = Marshal.SizeOf(typeof(T)); var bytes = reader.ReadBytes(sz); using (var ptr = new PinnedObject(bytes)) return ((IntPtr)ptr).ToStructure(); } } }