How To: "Upsert" Into AppSettings
ASP.NET 2.0 allows developers to update or insert values into web.config programmatically. This allows senior ASP.NET developers to create an administration or support page to modify values into web.config sections - without tampering with the web.config file directly.
If I have a value I would like to update or insert into the <appSettings> section, I would like to make an idempotent call that will either UPdate or inSERT the key value pair. Thus some call this behavior - upsert. Here is a utility method that demonstrates what I want:
public static void UpsertAppSettings(string key, string value) { // Current is an instance of System.Configuration.Configuration AppSettingsSection appSettings = Current.AppSettings; // Does the key argument already exist in appSettings? if (!Array.Exists<string>(appSettings.Settings.AllKeys, delegate(string s) { return (s == key); })) appSettings.Settings.Add(key, value); else appSettings.Settings[key].Value = value; Current.Save(); }// method