An example of the c generic serialization object as a byte array

  • 2020-06-19 11:33:28
  • OfStack

Serialize objects into byte arrays


using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
        protected byte[] Serialize<T>(T t)
        {
            MemoryStream mStream = new MemoryStream();
            BinaryFormatter bFormatter = new BinaryFormatter();
            bFormatter.Serialize(mStream, t);
            return mStream.GetBuffer();
        }

Deserialize byte arrays as objects


using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
        protected T Deserialize<T>(byte[] b)
        {
            BinaryFormatter bFormatter = new BinaryFormatter();
            return (T)bFormatter.Deserialize(new MemoryStream(b));
        }


Related articles: