How to store key-value pairs in application settings at runtime?
-
05-07-2019 - |
Question
How can dynamic Key-value pairs of objects be stored in app.config in using the application settings api, at runtime?
I've been trying to get my head around, and I can't find any meaningful example or documentation.
I seems that .Net dictionary classes can't be serialized in XML to store them in app.config
Is the only way to do it by using custom XML serialized classes, or are there any other ways?
Solution 2
After some more searching net, I've found a very good (albeit very long) article which describes in dept the .Net configuration model:
Unraveling the Mysteries of .NET 2.0 Configuration
I also found something very usefull:
Configuration Section Designer
A visual studio adding for visually designing config sections and generating the coresponging XSD files. I hope someone finds this useful.
OTHER TIPS
You ought to be able to do something like this:
// Open App.Config of executable
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Add an Application Setting with a name Key and a Value stored in variable called Value
config.AppSettings.Settings.Add("Key", Value );
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);
Have always thought it was considered bad practice to change app.config during runtime. The app.config should be used for program setup and configuration; not for things that are dynamic that the application is actually modifying.
Suggest you create seperate "KeyValue.xml" file for dynamic objects.
Depending on what exactly you need, you may try System.Collections.ObjectModel.KeyedCollection<TKey, TValue>. This only works if you can derive the key for an item from the item itself, but in that case, it's fine for this purpose.
Is it a generic dictionary? If so: