How to configure appsettings in web config file dynamically in asp.net c#?

How to configure appsettings in web config file dynamically in asp.net c#?, someone asked me to explain?

In this article, I will show you how to dynamically manage xml configuration file c# asp.net. To configure webconfig file dynamically, open web config file using webconfigurationManager and check the key is exists or not. If appsetting is not configured , add a new key otherwise update the appsetting.

Code behind C#:

protected void Page_Load(object sender, EventArgs e)
        {
            UpdateSetting("UnobtrusiveJavaScriptEnabled", "true");
 
        }
 
        public void UpdateSetting(string key, string value)
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
            if (config.AppSettings.Settings[key] == null)
            {
               config.AppSettings.Settings.Add(key, value);
            }
            else
            {
                config.AppSettings.Settings[key].Value= value;
            }
            config.Save();
            ConfigurationManager.RefreshSection("appSettings");
        }

Description: Run the application, it will update the following property “UnobtrusiveJavaScriptEnabled” set to true and save the config file and then refreshes the section in the web.config file.

dynamically configure appsettings in web config file c#

Post your comments / questions