// Deserialize a version 2.0 object. public static void ReadVersion2(string path) { FileStream fs = new FileStream(path, FileMode.Open); DataContractSerializer ser = new DataContractSerializer(typeof(PersonVersion2)); Console.WriteLine("Deserializing new data to version 2 \n\n"); PersonVersion2 p2 = (PersonVersion2)ser.ReadObject(fs); fs.Close(); Console.WriteLine("The data includes the old ID field value. \n"); Console.WriteLine("\t (New) Name: {0}", p2.Name); Console.WriteLine("\t ID: {0} \n", p2.ID); }
// Create an instance of the version 2.0 class. It has // extra data (ID field) that version 1.0 does // not understand. static void WriteVersion2(string path) { Console.WriteLine("Creating a version 2 object"); PersonVersion2 p2 = new PersonVersion2(); p2.Name = "Elizabeth"; p2.ID = 2006; Console.WriteLine("Object data includes an ID"); Console.WriteLine("\t Name: {0}", p2.Name); Console.WriteLine("\t ID: {0} \n", p2.ID); // Create an instance of the DataContractSerializer. DataContractSerializer ser = new DataContractSerializer(typeof(PersonVersion2)); Console.WriteLine("Serializing the v2 object to a file. \n\n"); FileStream fs = new FileStream(path, FileMode.Create); ser.WriteObject(fs, p2); fs.Close(); }