Код для сериализации и десериализации с использованием двоичного форматера:
public static class BinarySerializer
{
public static byte[] Serialize<T>(T obj)
{
var serializer = new DataContractSerializer(typeof(T));
var stream = new MemoryStream();
using (var writer =
XmlDictionaryWriter.CreateBinaryWriter(stream))
{
serializer.WriteObject(writer, obj);
}
return stream.ToArray();
}
public static T Deserialize<T>(byte[] data)
{
var serializer = new DataContractSerializer(typeof(T));
using (var stream = new MemoryStream(data))
using (var reader =
XmlDictionaryReader.CreateBinaryReader(
stream, XmlDictionaryReaderQuotas.Max))
{
return (T)serializer.ReadObject(reader);
}
}
}
Использование:
public void TestBinarySerialization()
{
// Create the person object.
Person person = new Person { Name = "John", Age = 32 };
// Serialize and deserialize the person object.
byte[] data = BinarySerializer.Serialize<Person>(person);
Person newPerson = BinarySerializer.Deserialize<Person>(data);
// Assert the properties in the new person object.
Debug.Assert(newPerson.Age == 32);
Debug.Assert(newPerson.Name == "John");
}