SEKAR B

SEKAR B

  • NA
  • 1
  • 772

Unable to update App.Config using ConfigurationManager

Nov 5 2015 9:35 AM

I am building a C# based DLL that will be used by another exe to launch the user application. The GUI is rich with lot of parameter/value type of settings. I need to save the settings of the GUI and load if needed by user. I am trying to use the App.Config to save in the below format. The load part is implemented as follows and tested with a sample element:

Configuration config = ConfigurationManager.OpenExeConfiguration(this.GetType().Assembly.Location);  System.Configuration.AppSettingsSection appSettings = (System.Configuration.AppSettingsSection)config.GetSection("Test1"); if (appSettings.Settings.Count != 0) { string m_bits = appSettings.Settings["Key1"].Value; }

But in the Save part I am using a similar approach like as below:

Configuration configuration = ConfigurationManager.OpenExeConfiguration(this.GetType().Assembly.Location);  System.Configuration.AppSettingsSection appSettings5 = (System.Configuration.AppSettingsSection)configuration.GetSection("Test1");  if (ConfigurationManager.AppSettings[key] == null) {   configuration.AppSettings.Settings.Add(key, value); } else {   configuration.AppSettings.Settings[key].Value = value; }  configuration.Save();

I am getting an error that Section or group name 'appSettings' is already defined. Updates to this may only occur at the configuration level where it is defined.

Basically, I want to save config from GUI to APP.Config and load the same whenever user wants to? While doing so I want to just update the APP.Config and doesnt want to create/clear the existing contents.

Actually I wanted to know the below inputs. Please suggest

  1. If this is right approach for Load/Save App.Config.
  2. Should I use XmlDoc approach?

Thanks