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

5 Comments

  • Does this physically updated the web.config file, or is it just for the session, or what? If not, when does it revert back?

  • Dested,

    Yes, this does physically change the web.config file. Thus, it is important to know that each time this is called, it will cause an application shut down.

  • "I would like to make an idempotent call that will either UPdate or inSERT the key value pair. Thus some call this behavior - upsert. "
    And some of us radials call this behavior "Set"....

    But you got me on idempotent - had to look that one up.

  • Oskar,

    Of course, I agree that this is simply "set"ting a value. I came across the term Upsert from a DBA who made stored procedures behave the same way.

    As far as idempotent - the context was purely on the end state of the call. Regardless of how I call it (or how many times I call it) the end state is the same.

  • I tried doing this but I didn't make it work.

Comments have been disabled for this content.