Funny – this approach is so darned simple, I am surprised why I hardly find anyone who actually uses it.
Check this out. Let us say, I wish to create an application in which I wish to keep the title of the form and it’s background color configurable, i.e. easily changeable after the application is compiled/deployed. How would I do this?
If you said “Config file” – oh you’d better keep reading.
Yes Config file will work. But there is an easier better way available. The “settings” file. No shit!! Follow these steps:
1. Create a Winforms app. Right click on the project and add a .settings file as shown below.
2. In the editor that pops up, add the values you wish to store.
You may note that in order to work with the above values, you get the appropriate editor. i.e. no more mistypes.
3. Type in the following code in Form.Load
private void Form1_Load(object sender, EventArgs e)
this.Text = WindowsAppSettings.Default.ApplicationTitle;
this.BackColor = WindowsAppSettings.Default.FormColor ;
You would note, full intellisense goodness as you are typing this code.
4. Run the application – seems to work eh?
You would note that the settings file is nothing but a plain XML file as shown below.
<?xml version='1.0' encoding='utf-8'?>
<Setting Name="ApplicationTitle" Type="System.String" Scope="Application">
<Value Profile="(Default)">Some Sample Title</Value>
<Setting Name="FormColor" Type="System.Drawing.Color" Scope="Application">
This magic is done by automatically creating a class in the background that strongly typed maps the above values.
Of course, this can be used for more than just global application level configuration settings. It can also support profiles/user level settings.
But I thought this was a cool neat little trick to share. Now I’m hoping you won’t have to create a custom config section, just for the heck of it.