To add key,value pair to appsetting tag of web.config
String key = "abc";
String value = "123";
bool isPresent=ConfigurationManager.AppSettings.AllKeys.ToList().Contains(key);
if (isPresent)
{
// label lblKeyValue
lblKeyValue.Visible = true;
lblKeyValue.Text = "Key has already entered";
}
else
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
config.AppSettings.Settings.Add(key, value);
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("appSettings");
}
To delete key,value pair of appsetting tag in web.config
String key = "abc";
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
config.AppSettings.Settings.Remove( key );
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("appSettings");
To Update key,value pair of appsetting tag in web.config
string key = "abc";
string value = "456";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
int k = xmlDoc.DocumentElement.ChildNodes.Count;
for (int i = 0; i < k; i++)
{
XmlNode childnode = xmlDoc.DocumentElement.ChildNodes[i];
if (childnode.Name == "appSettings")
{
foreach (XmlNode node in childnode)
{
if (node.Attributes[0].Value.Equals(key))
{
node.Attributes[1].Value = value;
}
}
}
}
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
ConfigurationManager.RefreshSection("appSettings");