Administrator

Administrator

  • Tech Writer
  • 2.2k
  • 1.5m

Object versions when serializing

Mar 5 2003 1:33 PM
I am having trouble getting the version of a previously saved object when deserializing the object. When you use the binaryformatter, the specific type version information is saved in the serialization process, but how do you get that information in deserialization? Or, what do you do when the object has changed from previous versions? There is an AssemblyName field avaliable in the SerializationInfo object passed into the constructor, but it represents the version of the current object, not the previously saved object. Is that correct? I've looked for an example showing how to handle versions in serialization, but I've found none. Here is some of the code I'm using: [Serializable()] public class ObjectC : ISerializable { public Object1 someObject; public DateTime createdDate; public string someString; /// /// Initializes a new instance of the ObjectC class. /// public ObjectC() { someObject = new Object1(); createdDate = DateTime.Now; someString = "This is object C"; } //Deserialization constructor. public ObjectC (SerializationInfo info, StreamingContext context) { // I want version information here... createdDate = (DateTime)info.GetValue("CreatedDate", typeof(DateTime)); someString = (string)info.GetValue("SomeString", typeof(string)); //Allows MyClass2 to deserialize itself someObject = new Object1(info, context); } //Serialization function. public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("CreatedDate", createdDate); info.AddValue("SomeString", someString); someObject.GetObjectData(info, context); } } private void Save(ObjectC obj) { Stream stream ; SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.InitialDirectory = @"C:\Temp\SerializationExample" ; saveFileDialog1.Filter = "bin files (*.bin)|*.bin|All files (*.*)|*.*" ; saveFileDialog1.FilterIndex = 0 ; saveFileDialog1.RestoreDirectory = true ; if(saveFileDialog1.ShowDialog() == DialogResult.OK) { if((stream = saveFileDialog1.OpenFile()) != null) { IFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, obj); stream.Close(); } } } private ObjectC Load() { ObjectC obj; Stream stream; OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.InitialDirectory = @"C:\Temp\SerializationExample" ; openFileDialog1.Filter = "bin files (*.bin)|*.bin|All files (*.*)|*.*" ; openFileDialog1.FilterIndex = 0 ; openFileDialog1.RestoreDirectory = true ; if(openFileDialog1.ShowDialog() == DialogResult.OK) { if((stream = openFileDialog1.OpenFile())!= null) { IFormatter formatter = new BinaryFormatter(); obj = formatter.Deserialize(stream); stream.Close(); } } return obj; }