troubleshooting Question

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

Avatar of jackjohnson44
jackjohnson44 asked on
.NET ProgrammingC#
1 Comment1 Solution700 ViewsLast Modified:
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;
        }
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 1 Comment.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 1 Comment.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros