Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify my App.exe.config keys at runtime?

In my app.config I have this section

<appSettings>     <add key ="UserId" value ="myUserId"/>      // several other <add key>s </appSettings> 

Usually I access the values using userId = ConfigurationManager.AppSettings["UserId"]

If I modify it using ConfigurationManager.AppSettings["UserId"]=something, the value is not saved to the file, and next time I load the application, it uses the old value.

How can I change the value of some app.config keys during runtime?

like image 845
Louis Rhys Avatar asked Mar 29 '11 05:03

Louis Rhys


2 Answers

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  config.AppSettings.Settings["UserId"].Value = "myUserId";      config.Save(ConfigurationSaveMode.Modified); 

You can read about ConfigurationManager here

like image 101
Rafal Spacjer Avatar answered Oct 09 '22 21:10

Rafal Spacjer


On a side note.

If something in your app.config needs to change at runtime...its possible there's a better place to keep that variable.

App.config is used for constants. At worst case something with a one time initialization.

like image 31
Whimsical Avatar answered Oct 09 '22 21:10

Whimsical