Skip to content

Instantly share code, notes, and snippets.

@GrabYourPitchforks
Created August 14, 2020 01:01
Show Gist options
  • Save GrabYourPitchforks/ed3d4e86a4dd2529af7390c946c6abce to your computer and use it in GitHub Desktop.
Save GrabYourPitchforks/ed3d4e86a4dd2529af7390c946c6abce to your computer and use it in GitHub Desktop.
BinaryFormatter binder sample
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
class Program
{
static void Main(string[] args)
{
Stream inputStream = GetInputStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Binder = new MySerializationBinder();
Person deserialialized = (Person)formatter.Deserialize(inputStream);
}
}
[Serializable]
public class Person
{
public string FirstName;
public string LastName;
}
class MySerializationBinder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
// If the input stream contained the old assembly name for this type,
// return typeof(...) to tell the serializer that it should map the
// old names to the specified Type.
if (typeName == typeof(Person).FullName && assemblyName == "OldAssembly, Version=1.0.0.0, ...")
{
return typeof(Person);
}
return null; // let the default binder logic kick in
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment