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?
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.
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.
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.
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