0

Say I created a data class some time ago:

[Serializable]
public class MyData
{
  public string name;
  public string nickname;
  public int id;
}

And I used BinaryFormatter to serialize and save users' data to a file. After time has passed, I decide we no longer need the field "nickname," so I remove it:

[Serializable]
public class MyData
{
  public string name;
  public int id;
}

However, now when I try to deserialize an object that was serialized when it still contained the nickname field, it throws an exception:

System.Runtime.Serialization.SerializationException: Field "nickname" not found in class MyData

Is there a way to tell the BinaryFormatter that if it encounters the field nickname to just ignore it and deserialize the rest of the fields as normal?

inejwstine
  • 678
  • 1
  • 10
  • 30
  • There are possible solutions, but none that sound like an easy fix (https://stackoverflow.com/questions/25108395/ignore-obsolete-field-when-deserializing) – Ryan Wilson Oct 26 '18 at 15:53
  • You'll have to put it back if you don't want to implement ISerializable. – Hans Passant Oct 26 '18 at 16:06
  • You can consider using serialization surrogate. https://stackoverflow.com/questions/13166105/is-it-possible-to-do-net-binary-serialization-of-an-object-when-you-dont-have#16121346 – Cinchoo Oct 26 '18 at 16:12

1 Answers1

1

No, this is impossible. What you have to do is deserialize it to a class with the same structure as before, then manually migrate your old object to your new object, and save the new object for the future.

laptou
  • 6,389
  • 2
  • 28
  • 59