c# .net Adsense ADO.NET Linq Viruses/security asp.net MVC JQuery Angular-js Node-js SEO Java C++ SQL API Networking vb.net .Net Css JavaScript Generics c#.Net entity framework HTML Website host Website Construction Guide HTTP tutorial W3C tutorial Web Services JSON Psychology Ionic framework Angular ReactJS Python Computer Android
c# .net

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

| | ASP-NET , CSharp , webconfig

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.