using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; namespace Tango.Serialization { /// /// Represents a data serializer for serializing data using binary formatter. /// public class BinaryDataSerializer : IDataSerializer { /// /// Serialize object to a file. /// /// Type of specified object. /// The specified object. /// The full path to the file to write. public void SerializeToFile(T obj, string filePath) { using (FileStream fs = new FileStream(filePath,FileMode.Create)) { SerializeToStream(obj, fs); } } /// /// Deserialize object from a file. /// /// Type of object to deserialize. /// The full path of the data file. /// The resulting object. public T DeserializeFromFile(string filePath) { using (FileStream fs = new FileStream(filePath, FileMode.Open)) { return DeserializeFromStream(fs); } } /// /// Deserialize object from bytes. /// /// Type of object to deserialize. /// The full path of the data file. /// The resulting object. public T DeserializeFromBytes(byte[] bytes) { using (MemoryStream ms = new MemoryStream(bytes)) { ms.Position = 0; return DeserializeFromStream(ms); } } /// /// Serialize object to stream. /// /// Type of specified object. /// The specified object. /// The stream to write. public void SerializeToStream(T obj, Stream st) { BinaryFormatter f = new BinaryFormatter(); f.Serialize(st, obj); } /// /// Serialize object to byte array. /// /// Type of specified object. /// The specified object. /// The stream to write. public byte[] SerializeToBytes(T obj) { using (MemoryStream ms = new MemoryStream()) { SerializeToStream(obj, ms); return ms.ToArray(); } } /// /// Deserialize object from stream. /// /// Type of object to deserialize. /// Stream to read from. /// The resulting object. public T DeserializeFromStream(Stream st) { BinaryFormatter f = new BinaryFormatter(); return (T)f.Deserialize(st); } /// /// Returns the serializer full name. /// /// public override string ToString() { return SerializationHelper.GetSerializerName(this); } } }