Link to home
Start Free TrialLog in
Avatar of jackjohnson44
jackjohnson44

asked on

c# xml serialize a class - if I change the class I can't deserialize file how can I fix?

I have two static functions below which I use to serialize and deserialize classes into files.  So for example, I do some things to a class on a form, save it to a file, then when I open the file, I rehydrate it.  If I change the class I can't open it again because the xml doesn't match.  Is there a way I can add properties to the class and be able to rehydrate using my old xml?  I don't mind setting default values for any new variables.  For example, if I want to create an IsActive boolean property set to false by default, I'd like to be able to do that without having to recreate the xml.






        public static void SerializeObjectToFile<T>(this T source, string path)
        {
            //XmlModelController.XmlSerializeToFile<T>(path, source);
            string serializedModel = String.Empty;

            var stringWriter = new StringWriter();
            try
            {
                new XmlSerializer(typeof(T)).Serialize(stringWriter, source);
                serializedModel = stringWriter.ToString();
            }
            finally
            {
                stringWriter.Dispose();
            }

            File.WriteAllText(path, serializedModel);
        }

        //this new thing on the end allows me to new up a T, if I didn't have it I would pass back a null object
        public static T XmlDeSerializeFile<T>(this T source, string filePath) where T : new()
        {
            //if it doesn't exist return a blank one
            //T returnValue = default(T);
            T returnValue = new T();
            if (File.Exists(filePath))
            {
                var reader = new StreamReader(filePath);
                try
                {
                    returnValue = (T)new XmlSerializer(typeof(T)).Deserialize(reader);
                }
                finally
                {
                    reader.Dispose();
                }
            }
            return returnValue;
        }
ASKER CERTIFIED SOLUTION
Avatar of Jacques Bourgeois (James Burger)
Jacques Bourgeois (James Burger)
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial