3

In a Console Application project Im trying to write values to the app.config file and save it permanently but are only able to save it in memory. I've tried all the solutions in Write values in app.config file but none works for me.

Any ideas what to do to make the change be permanently?

app.config file:

<appSettings>
    <add key="test" value="123456" />
</appSettings>

Class with two methods only saving value to memory:

public static class ConfigurationHelper
{

    public static void SetSetting(string key, string value)
    {
        Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        configuration.AppSettings.Settings[key].Value = value;
        configuration.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");
    }


    public static void SetSetting2(string key, string value)
    {
        Configuration configuration = ConfigurationManager.
            OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
        configuration.AppSettings.Settings[key].Value = value;
        configuration.Save();
        ConfigurationManager.RefreshSection("appSettings");
    }

}

Simple test that writes out the changes but when rebuild the project or opening app.config in notepad the changes are not saved:

[Test]
public void FirstTest()
{
    Console.WriteLine("Value before: " + ConfigurationHelper.Get<string>("test"));
    ConfigurationHelper.SetSetting2("test", "NewValue");
    Console.WriteLine("Value after: " + ConfigurationHelper.Get<string>("test"));
}
Community
  • 1
  • 1
Mr Null
  • 65
  • 2
  • 5
  • When you re-build your app it copies the app.config from your project into your output directory, overwriting it. Either don't do that, or copy the changes you've written back into the project file. – Peter Ritchie Feb 22 '17 at 16:39
  • Thanks, I think I understand the problem. Any ideas how to copy the changes from the output file back to the app.config file? – Mr Null Feb 23 '17 at 06:57

1 Answers1

6

As far as i know information from app.config is used while creating program but app.config keys and values are read-only, but you don't have to use app.config to store values in app, try using this:

step 1
go to solution explorer -> Properties -> Settings and create settings file.
step 2
add settings you want to use
step 3
Use in code

add using yourNameSpace.Properties;

read value of setting:
var name = Settings.Default.Name1;

seting value of setting:
Settings.Default.Name1 = value;

saving settings:
Settings.Default.Save();

Hope it helped you.

Maciej Kozieja
  • 1,812
  • 1
  • 13
  • 32