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"));
}
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.