Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the value in app.config file dynamically

Tags:

c#

.net

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?

like image 303
Partha Avatar asked Aug 31 '09 12:08

Partha


People also ask

Can we dynamically change the key value in web config?

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.

Is app config the same as web config?

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.


3 Answers

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.

like image 170
Adis H Avatar answered Oct 05 '22 20:10

Adis H


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");
like image 36
Pierre-Alain Vigeant Avatar answered Oct 05 '22 19:10

Pierre-Alain Vigeant


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");
like image 43
CCondron Avatar answered Oct 05 '22 21:10

CCondron