using System; using System.Threading.Tasks; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace Nibriboard.Utilities { public static class BinaryIO { /// /// Deserialises an object from it's binary representation. /// /// The type to cast the deseralised object into. /// The source stream to deseralise an object from. /// The object deserialised from the given stream. public static async Task DeserialiseBinaryObject(Stream sourceStream) { return await Task.Run(() => { BinaryFormatter formatter = new BinaryFormatter(); return (T)formatter.Deserialize(sourceStream); }); } /// /// Serialises an object and outputs a binary representation to the given stream. /// /// The target to serialise. /// The destination stream to send the binary representation to. public static async Task SerialiseToBinary(object target, Stream destinationStream) { await Task.Run(() => { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(destinationStream, target); }); } } }