Is there a best practices for storing UI settings in a file?<>
This question already has an answer here:
- Best practices for storing UI settings? 7 answers
You can also define a custom configuration section and then put the settings in a separate config file if you didn't want to clutter up your app.config. A custom configuration module allows you to define a structure for your own complex settings and store them in a standard config file. If you have used Entity Framework, Enterprise Library or the like, then you have probably seen them defined at the top of the file. A quick search on Google turned up another StackOverflow post on the subject.
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:
- Install NewtonSoft.JSON using Nuget package manager
- Add reference to this library to your project and .cs file (using NewtonSoft.Json)
- Create a C# class for your config settings. For repeating blocks you may use List<string> or any other relevant data type, even int - so you don't have to do any type conversion too.
- Read JSON file into a string object
- Use JsonConvert.DeserializeObject() as:
MyConfigSettings settings = JsonConvert.DeserializeObject<MyConfigSettings>(jsonString);
Here MyConfigSettings is the configuration settings class. The corresponding members will have to be declared as public properties with proper get; 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.