How to properly store state in a C # .Net application

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

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

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

+2


source to share


6 answers


I would prefer to store your state in a database if possible, or in a different file structure. Changing your app.config at runtime is usually not done. I would much rather serialize your object to a file and use that to save its state.

This will dynamically change app.config or web.config if possible.



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");
}

      

+6


source


You can also use IsolatedStorage



+2


source


What's wrong with app settings? This is the easiest way to save the settings (hence the name) as you set it up in the designer and can access it through an auto-generated class, just like auto-generated resource classes. This data will be saved in the application data directory. WinForms applications have a default settings file, but you can easily create additional ones.

It also doesn't support dynamic key / value pairs, but you can get around this with a dictionary (although Dictionary<TKey, TValue>

not serializable to XML, you have to get around this, for example using a list KeyValuePair

or KeyedCollection

for storage).

+2


source


If you don't want to use app config or registry then you can also check BinaryFormatter and XmlSerializer . BinaryFormatter will be version dependent, while XmlSerializer allows for more editable human files and also makes sharing and updating easier 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; }
}

      

+1


source


You can use application settings (settings file) and store the state information there as a key value structure (dictionary, custom object list or whatever). You can find more details here on using app preferences and user preferences in C #: http://msdn.microsoft.com/en-us/library/aa730869%28VS.80%29.aspx Application preferences will be saved in app. config and user preferences in isolated user storage.

+1


source


I would serialize objects in xml file on exit and deserialize on startup. This way, when your objects change, all properties are preserved.

0


source







All Articles