c# SerializationBinder Array of Strings/ Bytes BindToType Notworking

172 Views Asked by At

I'm using SerializationBinder like below code which is working for Item class.


namespace TestBinder
{
  class Program
  {
    static void Main(string[] args)
    {
      string[] cars = { "Volvo", "BMW", "Ford", "Mazda" };

      var item = new Item
      {
        Name = "Orange"
      };

      var bytes = SerializeData(item);      
      var deserializedData = DeserializeData(bytes);
    }

    private static byte[] SerializeData(object obj)
    {
      var binaryFormatter = new BinaryFormatter();
      using (var memoryStream = new MemoryStream())
      {
        binaryFormatter.Serialize(memoryStream, obj);
        return memoryStream.ToArray();
      }
    }
    private static object DeserializeData(byte[] bytes)
    {
      var binaryFormatter = new BinaryFormatter
      {
        Binder = new TestSerializationBinder()
      };

      using (var memoryStream = new MemoryStream(bytes))
        return binaryFormatter.Deserialize(memoryStream);
    }
  }
  [Serializable]
  public class Item
  {
    private string _name;
    public string Name
    {
      get { return _name; }
      set { _name = value; }
    }
  }
  public class TestSerializationBinder : SerializationBinder
  {
    public override Type BindToType(string assemblyName, string typeName)
    {
      if (typeName.Equals("TestBinder.Item"))
        return typeof(Item);
      if (typeName.Equals("System.String[]"))
        return typeof(string[]);
      return null;
    }
  }
}

Breakpoint in the BindToType hits when using Item class. Instead of item if cars(which is array of string) is sent for SerializeData then when deserilizing the same BindToType method is not invoked.

Please suggest how to use BindToType when deserializing data which is of type "array of strings or bytes"

1

There are 1 best solutions below

1
AVTUNEY On

This will work. You can use more case if you want.

    public override Type BindToType(string assemblyName, string typeName)
    {
        switch (typeName)
        {
            case "TestBinder.Item":
                return typeof(Item);
            case "System.String[]":
                return typeof(string[]);
            default:
                throw new ArgumentException($"Unrecognized typename {typeName}", nameof(typeName));
        }
    }

P.S returning a null is not a good practice. You could just throw ArgumentException.