In this article I am going to show how we can make changes
in our web.config file at run time.
If you want to add a new key in your web.config file at run
time then use below code…
Configuration config =
WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
config.AppSettings.Settings.Add(TxtYourKey.Text, TxtYourValue.Text);
config.Save();
lblMsg.Text = " Successfully added new key in config
file";
TxtYourKey.Text = null;
TxtYourValue.Text = null;
If you
want to delete a existing key then use below code…
Configuration
config =
WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
config.AppSettings.Settings.Remove(TxtYourKey.Text);
config.Save();
lblMsg.Text = "key deleted from config file";
TxtYourKey.Text = null;
If you
want to display all key in your web.config file then use below code…
Configuration configuration =
WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection appSettingsSection =
(AppSettingsSection)configuration.GetSection("appSettings");
if (appSettingsSection != null)
{
foreach
(string key in appSettingsSection.Settings.AllKeys)
{
Response.Write(key);
}
}
If you
want to to modify an existing key then use below code…
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;
config.Save();
}
}