Wednesday, 17 November 2010

Changing App.config contents at runtime

Sometimes it is required to change the contents of ‘App.config’ file. Assume if we are allowing user to override things like taxrates, which we keep on the ‘App.config’.
On the App.config, we have a key ‘TaxRate’ which has the value ‘15’.
   1: <?xml version="1.0" encoding="utf-8" ?>
   2: <configuration>
   3:     <appSettings>
   4:         <add key="TaxRate" value="15"/>
   5:     </appSettings>
   6: </configuration>

And we have to change it to ‘20’. We can use the following syntax:


   1: Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
   2: AppSettingsSection appSection = config.AppSettings;
   3:  
   4: appSection.Settings["TaxRate"].Value = "20";
   5: config.Save(ConfigurationSaveMode.Modified,false);
   6:  
   7: ConfigurationManager.RefreshSection("appSettings");
   8: string zVal = ConfigurationManager.AppSettings["TaxRate"];
**Please note : The changes are temporary, when running on debug mode. But will be permanent when run using the built application (Executable)

No comments:

Post a Comment