tags:

views:

226

answers:

6

I have a list of objects, where each object has a boolean property named "enabled". I want to remember the state of these objects accross application sessions. To do this I have at least 2 options, using the registry or using, the more .net approach, app.config file. I would prefer to do the latter.

However, while static/compiletime key/value assignment is trivial, assigning new keys dynamically to the app.config file seems nontrivial. Do you have an example of how to do this?

My question is, what is the best approach to store properties of a list of objects in .net if you want to avoid the registry?

+6  A: 

I would favor saving your state to a database if possible or another file structure. Changing your app.config at run-time is generally not done. I would favor serializing your object to a file, and using that to keep it state.

This will dynamically change the app.config or web.config as the case maybe.

public void ChangeAppSettings(string applicationSettingsName, string newValue)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    KeyValueConfigurationElement element = config.AppSettings.Settings[applicationSettingsName];

    if (element != null)
    {
        element.Value = newValue;
    }
    else
    {
        config.AppSettings.Settings.Add(applicationSettingsName, newValue);
    }

    config.Save(ConfigurationSaveMode.Modified, true);

    ConfigurationManager.RefreshSection("appSettings");
}
David Basarab
Hi, and thanks for you extensive answer. I believe that an database would be overkill in my case. But just for the completness of the thread, is it true that the registry is generally avoided in .net apps?
Sideshow Bob
The registry is not avoided, just like anything it depends on your implementation. In .NET it is preferred to use a .config file to configure your application, not save state. But that is preferred not required. You must determine your best solution for the problem you are trying to solve. Sometimes that is the registry sometimes it is a config.
David Basarab
+1  A: 

If you don't want to use the app config or the registry you can also check out BinaryFormatter and XmlSerializer. BinaryFormatter will be version dependant while XmlSerializer allows for more human editable files, as well as, easier sharing and upgrading for other projects.

class Program
{
    static void Main(string[] args)
    {
        var obj = new MyObject() { Prop1 = "Hello World!!!" };
        //===
        var bf = new BinaryFormatter();
        using (var fs = File.Open("myobject.bin", FileMode.Create, 
                                  FileAccess.Write, FileShare.None))
            bf.Serialize(fs, obj);
        //===
        MyObject restoredObj = null;
        using (var fs = File.OpenRead("myobject.bin"))
            restoredObj = bf.Deserialize(fs) as MyObject;

        //===
        var xSer = new XmlSerializer(obj.GetType());
        using (var fs = File.Open("myobject.xml", FileMode.Create, 
                                  FileAccess.Write, FileShare.None))
            xSer.Serialize(fs, obj);
        //===
        MyObject restoredObjXml = null;
        using (var fs = File.OpenRead("myobject.xml"))
            restoredObjXml = xSer.Deserialize(fs) as MyObject;

    }
}

[Serializable()]
[XmlRoot("myObject")]
public class MyObject
{
    [XmlAttribute("prop1")]
    public string Prop1 { get; set; }
}
Matthew Whited
A: 

I would serialize the objects to an xml file on exit, and deserialize on startup. This way as your objects change, all properties are maintained.

NerdFury
I might have expressed myself a little unclear. My primary goal is not to save the state of all properties in the objects collection of objects. I just wantet to "remember" certain properies of a collection of objects. For instance, a number representing a sort order, stored in each object.
Sideshow Bob
+2  A: 

You can also use the IsolatedStorage

Locksfree
+1  A: 

What's wrong with application settings? It's the simplest way to store settings (hence the name), since you set it up in the designer and can access it through an auto-generated class, much like the auto-generated resource classes. This data will be stored in the application data directory. There is a default settings file in a WinForms applications, but you can create additional ones easily.

It does not support dynamic key/value pairs either, but you can get around that by using a dictionary (though Dictionary<TKey, TValue> does not serialize to XML, you have to work around that, like using a KeyValuePair list or KeyedCollection for storage).

OregonGhost
app settings are fine. I personally use them with custom persistance. That way I can have the app.conf pass a URI to my XmlSerializer. That URI can later be redirected from a local file, to a network share, or even a RESTful webservice without changing my app.
Matthew Whited
A: 

You could use application settings (.settings file) and store your state information there as a key-value structure (dictionary, list of custom objects or whatever). Here you can find more details about using app settings and user settings in C#: http://msdn.microsoft.com/en-us/library/aa730869%28VS.80%29.aspx The app settings will be stored in app.config and the user settings in the user's isolated storage.