Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

App.Config change value

Tags:

c#

app-config

This is my App.Config

<?xml version="1.0" encoding="utf-8" ?> <configuration>   <appSettings>     <add key="lang" value="English"/>   </appSettings> </configuration> 

With this code I make the change

lang = "Russian"; private void Main_FormClosing(object sender, FormClosingEventArgs e) {      System.Configuration.ConfigurationManager.AppSettings.Set("lang", lang); } 

But it not change. What I'm doing wrong?

like image 875
a1204773 Avatar asked Jun 22 '12 02:06

a1204773


People also ask

How read and write config file in C#?

The easiest way to read/write AppSettings config file there is a special section in reserved which allows you to do exactly that. Simply add an <appsettings> section and add your data as key/value pairs of the form <add key="xxx" value="xxxx" /> . That's all to create a new app. config file with settings in it.

What is AppSettings in app config?

The <appSettings> element stores custom application configuration information, such as database connection strings, file paths, XML Web service URLs, or any other custom configuration information for an application.


1 Answers

AppSettings.Set does not persist the changes to your configuration file. It just changes it in memory. If you put a breakpoint on System.Configuration.ConfigurationManager.AppSettings.Set("lang", lang);, and add a watch for System.Configuration.ConfigurationManager.AppSettings[0] you will see it change from "English" to "Russian" when that line of code runs.

The following code (used in a console application) will persist the change.

class Program {     static void Main(string[] args)     {         UpdateSetting("lang", "Russian");     }      private static void UpdateSetting(string key, string value)     {         Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);         configuration.AppSettings.Settings[key].Value = value;         configuration.Save();          ConfigurationManager.RefreshSection("appSettings");     } } 

From this post: http://vbcity.com/forums/t/152772.aspx

One major point to note with the above is that if you are running this from the debugger (within Visual Studio) then the app.config file will be overwritten each time you build. The best way to test this is to build your application and then navigate to the output directory and launch your executable from there. Within the output directory you will also find a file named YourApplicationName.exe.config which is your configuration file. Open this in Notepad to see that the changes have in fact been saved.

like image 97
Kevin Aenmey Avatar answered Oct 08 '22 19:10

Kevin Aenmey