Tuesday, February 2, 2010

C# - Manipulating the appSettings section of the configuration file at runtime

There might be a time wherein you have to manipulate the configuration at runtime, either adding or removing key-value pair. Below are some code snippets in C# to do this.

Adding a new appSetting value:
Configuration config = WebConfigurationManager.OpenWebConfiguration("/WebPersonalExercises");

AppSettingsSection appSection = ((AppSettingsSection)(config.GetSection("appSettings")));

KeyValueConfigurationCollection keyVal = appSection.Settings;

keyVal.Add("myNewValue", "value" + ++intCounter);

config.Save();

Removing the value:
Configuration config = WebConfigurationManager.OpenWebConfiguration("/WebPersonalExercises");

AppSettingsSection appSection = ((AppSettingsSection)(config.GetSection("appSettings")));

KeyValueConfigurationCollection keyVal = appSection.Settings;

keyVal.Remove("myNewValue");

config.Save();

Note that if you add the same appSetting key multiple times, it would be presented in the file like this (concatenated with a comma separator):
<appSettings>
  <add key="myNewValue" value="value1,value2,value3"/>
</appSettings>

But when you call the remove method, all of the appSetting key-value would be removed, regardless of how many times you add the same appSetting key of different values.

No comments:

Post a Comment