views:

74

answers:

2

I have a settings class that I want to be able to serialize and deserialize to save and load settings to a file.

With hindsight, I'd have designed my whole app to create an instance of settings when needed. As it is, my settings are persistent (mimicking the default application settings behaviour). Given my current architecture, I can do the following:

public void Save()
{
    Stream stream = File.Open("settings_test.xml", FileMode.Create);
    XmlSerializer x = new XmlSerializer(this.GetType());
    x.Serialize(stream, this);
}

Obviously, I can't do this:

public void Load()
{
    Stream stream = File.Open("settings_test.xml", FileMode.Open);
    XmlSerializer x = new XmlSerializer(this.GetType());
    this = x.Deserialize(stream);
}

But is there a way to update all the public properties of the current class to match those of the deserialized object?

(I suppose the more general questions is: "Is there an efficient way to update one class based on the contents of another?")

+2  A: 

I would use a static method

MyClass myclass = MyClass.Load("settings.xml")

Otherwise you can achive that with reflection.

Found this example via google: http://www.csharp-examples.net/reflection-examples/

SchlaWiener
Thanks, ended up going for the former option.
Tom Wright
+2  A: 

I would make the settings class an singelton and have a static Instance to it then you could call load and save on that instance

public class MySettings
{
    private static MySettings _instance;
    public static MySettings Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new MySettings();
                // maby call Load();
            }
            return _instance;
        }
    }
    private MySettings()
    {  
        //set default values
    }

    public void Load()
    {
        Stream stream = File.Open("settings_test.xml", FileMode.Open);
        XmlSerializer x = new XmlSerializer(this.GetType());
        _instance = (MySettings)x.Deserialize(stream);
    }

    public void Save()
    { 
        Stream stream = File.Open("settings_test.xml", FileMode.Create);
        XmlSerializer x = new XmlSerializer(this.GetType());
        x.Serialize(stream, _instance);
    }
}
LiFo
That is what I would recommend, too. Hide the details of loading behind a static access property. One side note though: the stream should be wrapped in a using statement, to ensure proper cleanup.
Gnafoo