Tuesday, December 10, 2013

Update app config values in run time using C#

Normally we use app.config file to store some config values. as we all know, we can easily read values from app.config using C#. but we rarely update that file in run time. but this is also possible in C#.
here i have explained how to write back(Add new keys or update values of certain key) to app.config file in run time.


/// <summary>
/// Update app config values
/// </summary>
 /// <param name="key">app config key</param>
/// <param name="value">app config value</param>

public static void UpdateAppSettings(string key, string value)
{
          // Give the correct path of an app.config file
          Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (ConfigurationManager.AppSettings[key] == null)
            {
                config.AppSettings.Settings.Add(key, value);
            }
            else
            {
                config.AppSettings.Settings[key].Value = value;
             
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");          
}

Write a main method and call this function to update app.config values. cool :)