Add, Modify, Remove appSettings keys and values in web.config

 
When you go through this article then you will find three function(Add,Modify and Remove) . Add and Modify function have two argument Key and value where Key is the name of key and value is value contain on the key and Remove function have one argument key name. Just pass value according to function parameter.


If developer want to add connection string or any other key value in appSettings at run time in web.config.
[C#]

 public void add(string key, string value)
    {
 
        Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
        AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
        if (appSettingsSection != null)
        {
            appSettingsSection.Settings.Add(key, value);
            configuration.Save(ConfigurationSaveMode.Modified);
            configuration.Save();
        }
    }

If developer want to Modify connection string or any other key value in appSettings at run time in web.config.

[C#]

public void Modify(string key, string value)
    {
 
        Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
        AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
        if (appSettingsSection != null)
        {
            appSettingsSection.Settings[key].Value = value;
            configuration.Save();
        }
    }

If developer want to Remove connection string or any other key value in appSettings at run time in web.config.

[C#]

    public void Remove(string key)
    {
 
        Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
        AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
        if (appSettingsSection != null)
        {
            appSettingsSection.Settings.Remove(key);
            configuration.Save();
        }
    }

Author: Pavan

I am asp.net developer have good knowledge of Asp.net ver 05,08,10 and good hand in sql server.Proficient in Object Oriented Programming and javascript, jQuery. Achievements - Integrate Spotfire, appnexus API ASP.net with sql server. Hobbies - Blogging ,Games, Movies ,Teaching,Keeping myself update with new technologies

One thought on “Add, Modify, Remove appSettings keys and values in web.config”

Comments are closed.