I want to modify a value in appSetting section in app.config. So i wrote,
Console.WriteLine(ConfigurationManager.AppSettings["name"]);
Console.Read();
Configuration config=ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["name"].Value = "raja";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
Console.WriteLine(ConfigurationManager.AppSettings["name"]);
Console.Read();
after the execution of above code, i verified the app.config whether the value of "name" element has been changed or not. but no change.
what is the wrong with my code? or is there any other way to do this?
The sample source code allows you to change the key and value pair. There is no need to open web. config file. The application also allows you to update and delete the key/value pair.
Web. Config is used for asp.net web projects / web services. App. Config is used for Windows Forms, Windows Services, Console Apps and WPF applications.
This code works for me:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.Settings["test"].Value = "blah"; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings");
Note: it doesn't update the solution item 'app.config', but the '.exe.config' one in the bin/ folder if you run it with F5.
You have to update your app.config file manually
// Load the app.config file
XmlDocument xml = new XmlDocument();
xml.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
// Do whatever you need, like modifying the appSettings section
// Save the new setting
xml.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
And then tell your application to reload any section you modified
ConfigurationManager.RefreshSection("appSettings");
Expanding on Adis H's example to include the null case (got bit on this one)
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings["HostName"] != null)
config.AppSettings.Settings["HostName"].Value = hostName;
else
config.AppSettings.Settings.Add("HostName", hostName);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With