user360943
user360943

Reputation: 107

Updating a value in a local app.config

I've got an exe that reads some values from its local app.config file:

TargetDate = ConfigurationManager.AppSettings.Get("ThresholdDate");

// and try to update with the current date
ConfigurationManager.AppSettings.Set("ThresholdDate", "2011-09-01");

I thought it worked once, but am not seeing the app.config getting updated at all now.

Upvotes: 1

Views: 4471

Answers (3)

jersoft
jersoft

Reputation: 478

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

config.AppSettings.Settings["ThresholdDate"].Value = Convert.ToString(testdate);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

this will work only while your not in debuging mode. try to run yung code in /debug/appName.exe and the you will se the changes in appName.exe.config

cheers!

Upvotes: -1

user360943
user360943

Reputation: 107

Looking here: How to change App.config file run time using C# is the answer - while running in the visual studio IDE, you will not see the values persisted in the /bin/appname.exe.config. You actually have to go into the bin directory and run the exe.

So this code actually works, just not in debug mode:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

config.AppSettings.Settings["ThresholdDate"].Value = Convert.ToString(testdate);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

Upvotes: 2

Baz1nga
Baz1nga

Reputation: 15579

I think you can try something like this:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
//change the config value
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

I am not sure abt the syntax for changing the config value but I have done an Add before and I know you can do a remove so I guess you could do a combination of remove and add like this:

config.AppSettings.Settings.Remove("ThresholdDate");
config.AppSettings.Settings.Add("ThresholdDate", "2011-09-01");

Upvotes: 2

Related Questions