To add,update,delete key,value pair of appsetting tag in web.config

Teena
Posted by Teena under ASP.NET category on | Points: 40 | Views : 4698
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");

Comments or Responses

Posted by: Ndebata on: 4/25/2011 Level:Starter | Status: [Member] | Points: 10
Hi

To check whether key is already there or not, no need to load all xml in to memory and loop through it,
you can simply check in this array.
bool isPresent=ConfigurationManager.AppSettings.AllKeys.ToList().Contains("abc")

Posted by: Teena on: 4/25/2011 Level:Starter | Status: [Member] | Points: 10
Hi Debata

Thanks for your comments.

Thanks
Teena

Posted by: Rahultk on: 4/25/2011 Level:Starter | Status: [Member] | Points: 10
This is really useful.
Posted by: Teena on: 4/26/2011 Level:Starter | Status: [Member] | Points: 10
Thx Rahul

Login to post response