As others mentioned, you can do this with ConfigurationManager.AppSettings.Settings
. But:
Using Settings[key] = value
will not work if the key doesn't exist.
Using Settings.Add(key, value)
, if the key already exists, it will join the new value to its value(s) separated by a comma, something like
<add key="myKey" value="value1, value2, value3" />
To avoid these unexpected results, you have to handle two scenario's
Code
public static void Set(string key, string value)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var entry = config.AppSettings.Settings[key];
if (entry == null)
config.AppSettings.Settings.Add(key, value);
else
config.AppSettings.Settings[key].Value = value;
config.Save(ConfigurationSaveMode.Modified);
}
For more info about the check entry == null
, check this post.
Hope this will help someone.