Skip to content

Instantly share code, notes, and snippets.

@ArseniySavin
Last active December 6, 2019 12:50
Show Gist options
  • Save ArseniySavin/3c9cffe64ac2ca868ff87a9ee6ecdfd7 to your computer and use it in GitHub Desktop.
Save ArseniySavin/3c9cffe64ac2ca868ff87a9ee6ecdfd7 to your computer and use it in GitHub Desktop.
Binary serialize extension
public class BinaryModelSerialaizer
{
BinaryFormatter _binaryFormatter;
public BinaryModelSerialaizer(BinaryFormatter binaryFormatter)
{
_binaryFormatter = binaryFormatter;
}
public byte[] Serialize<T>(T obj)
{
using (MemoryStream s = new MemoryStream())
{
_binaryFormatter.Serialize(s, obj);
return s.ToArray();
}
}
public T Deserialize<T>(byte[] data)
{
using (MemoryStream s = new MemoryStream(data))
{
_binaryFormatter.Binder = new BinarySerializationBinder(typeof(T));
return (T)_binaryFormatter.Deserialize(s);
}
}
}
sealed class BinarySerializationBinder : SerializationBinder
{
Type _type;
public BinarySerializationBinder(Type type)
{
_type = type;
}
public override Type BindToType(string assemblyName, string typeName)
{
return _type;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment