Here's my own solution to a problem that seems to plague a lot of .NET developers out there. The problem is how best to enumerate application settings stored in a section of an ASP.NET 2.0 app.config file at runtime. Let's suppose you have a settings file called Color.settings with the following key-value pairs:
BLU - Blue
BRO - Brown
GRN - Green
HAZ - Hazel
The designer stores those settings in app.config. It also creates the getters for each key and decorates them with the value:
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("Blue")]
public string BLU {
get {
return ((string)(this["BLU"]));
}
}
In this way the Color class is strongly-typed and, given a code, makes it easy to fetch its value through the settings property:
string color = Color.Default.BLU;
But what if you don't know the key at design time? Fortunately, the singleton instance exposed by the Color.settings class implements ApplicationSettingsBase Properties. Reference System.Configuration and simply enumerate the SettingsPropertyCollection to find the value:
string key = "BLU";
string value = string.Empty;
foreach (SettingsProperty sp in Color.Default.Properties) {
if (sp.Name.Equals(key)) {
value = sp.DefaultValue.ToString();
break;
}
}