
Introduction
A class with a simple, easy to use interface, is ready to help every one to read/write application configuration in an effective way.
Background
First of all, I don't like ConfigurationSettings
provided by the .NET framework, as I can not change the config as I want in the App. I did see many articles on the topic, but either they are too big and complex, get me distracted, or can not meet my requirement. My goal is simple: provide a default setting when first launching the App, and on exit, "remember" the user's preference. Registry is another option, but I prefer XML files, which you can open and check more conveniently.
Using the code
All the settings is set by key/value pairs in an XML file, you can insert/update/delete any key/value. The three major public methods are: GetValue
, SetValue
, removeElement
, it's that simple. By default, the XML file should be put in the same folder as your EXE file.
GetValue, key= "CountryLoc"
Config config = new Config();
config.cfgFile = "app.config";
txtCountry.Text =
config.GetValue("//appSettings//add[@key='CountryLoc']");
I exposed //appSettings
in the interface, as you may need access to key/value in different sections. For instance, if you GetValue
from key1
in Company
section, you can use:
config.GetValue("//Company//add[@key='key1']");
If the section is new, you need to set it up, for example, manually add <Company> </Company>
into <configuration>...</configuration>
. As in my case, I only have one section, so if you do not like manual thing, you are very welcome to put your code to enhance it. SetValue
is quite similar:
config.SetValue("//appSettings//add[@key='"
+ txtKey.Text + "']", txtValue.Text);
txtKey.Text + "']", txtValue.Text);
Remove element:
config.removeElement("//appSettings//add[@key='" +
txtKey2.Text + "']");
Reference
This article is based on some code I found on the internet which I have forgotten where it is.