I have not seeing an satisfactory answer for this yet, so thought I'd ask. Are there any best practices for storing UI settings in a file?
The scenario is that we have an in house C# app that I want to store an array of file/folders in along with other random things (flags to use when executing an external command, optional arguments to pass to selectable compare algorithms, etc). Because of the nature of these values, using the built in app.config methods isn't going to work. So is there any best practices when storing semi-complex settings to an setting file?
Currently the most complex I'm storing will be a list with a single entry needing to store a file name, compare algorithm, and argument text. So it's not all simple key/value data.
I'm looking for thoughts on:
This won't be storing sensitive data, so security isn't a concern.
I'm currently looking to just use XmlDocument and separate classes for each different collection. But I feel like there should be some existing framework for this already.
Thank you!
You're right that such settings should not be stored in app.config file. It just adds clutter there. In this case it would be better to create another configuration file as you have already mentioned in your ticket.
You are planning to structure this config file as XML document. This is a great idea. This also means that your config data is structured. That's great too.
I would suggest you go for JSON. This would let you load config settings into your application at run-time with very few lines of code. Try NewtonSoft.JSON (aka. JSON.Net).
You may follow these steps to quickly add and use configuration settings:
List<string>
or any other relevant data type, even int
- so you don't have to do any type conversion too.JsonConvert.DeserializeObject()
as:MyConfigSettings settings = JsonConvert.DeserializeObject<MyConfigSettings>(jsonString);
Here
MyConfigSettings
is the configuration settings class. The corresponding members will have to be declared aspublic
properties with properget; set;
attributes defined.This would load all the configuration settings to the
settings
object. The best part is that any missing configuration values, will be automatically skipped so you don't have to have any complex parsing algorithms.
To write config values to a JSON file, you may populate values in the settings
object and serialize them using:
// Indented so that it looks readable when the config file is opened in editor like Notepad
string data = JsonConvert.SerializeObject<MyConfigSettings>(settings, Formatting.Indented);
// Now just store string object data to the config file
Note: This would require .Net 4.0+
A quick start is given in this example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With