0

I am trying to save some settings to the appSettings section of my configuration file so I may use the data to carry out the processes of the program. On the click of a button I want the data coming from the user to be saved in the config file. The code I am using is:

private void button1_Click(object sender, EventArgs e)
{

            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            config.AppSettings.Settings["key1"].Value = "value1";
            config.AppSettings.Settings["key2"].Value = "value2";

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");

}

Before the code is executed my app.config file looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
  </configSections>
  <appSettings>
    <add key="roshane" value=""/>
    <add key="email" value=""/>
    <add key="super" value=""/>
    <add key="phone" value=""/>
  </appSettings>
  <connectionStrings>
    <add name="AutoReportEmailerConnectionString"
        connectionString="Data Source=roshane\sqlexpress;Initial Catalog=ICR_v5.0;Integrated Security=True"
        providerName="System.Data.SqlClient" />
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
  </startup>
</configuration>

After the code is execute the programName.exe.config file is the same as the app.config. Is there something I am missing why the values are not being added to the programName.exe.config file?

russian
  • 207
  • 2
  • 4
  • 11

2 Answers2

0

config.Save(ConfigurationSaveMode.Modified) works only when you modify an exisint key in other words a key that was in the web config before if you need to actually add key values to the web config just call config.Save() with no parameters

Luis Palacios
  • 754
  • 13
  • 35
0

If you want to add new Key to config file, need to add it first in Settings collection:

config.AppSettings.Settings.Add("Key", "Value");

Then call Save method.

Vish
  • 46
  • 3