1

I wrote a basic settings storage class for user inputs that loads and saves data from a xml file. It works great when the xml has all the correct values.

However one of the values is an enum that has had some of it's accepted values changed in version updates. Because of this some users have xml settings files that are no longer compatible with the latest version.

Because I know all the possible previous values for this input, is it possible that when the deserializer encounters one of those values, it reads it as a different value?

public class UserInput
{
    //... long list of variables
    //enum that had its values changed from prior versions but still has the same name
    public MyEnum UserType { get; set; }

    private static XmlSerializer xs;

    static UserInput()
    {
        xs = new XmlSerializer(typeof(UserInput));
    }

    public void SaveToFile(string fileName)
    {
        using (StreamWriter sr = new StreamWriter(fileName))
        {
            xs.Serialize(sr, this);
        }
    }

    public static UserInput ReadFromFile(string fileName)
    {
        using (StreamReader sr = new StreamReader(fileName))
        {
            return xs.Deserialize(sr) as UserInput;
        }
    }
}

I'm hoping I can insert a check into the above code so that when my enum that has changed is encountered it can load it as a valid value.

  • Use a surrogate property as shown in [XmlSerializer with new enum values](https://stackoverflow.com/q/1621306) and [Instance validation error: * is not a valid value for *](https://stackoverflow.com/q/22245569) and [deserializing enums](https://stackoverflow.com/q/4250656). `[Obsolete]` is also an option, see [XmlSerializer: How to Deserialize an enum value that no longer exist](https://stackoverflow.com/q/10708240). – dbc Apr 27 '19 at 19:05

0 Answers0