app.config are not saving the values

流过昼夜 提交于 2020-01-12 14:49:13

问题


My App.Config is something like:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <appSettings>
  <add key="foo" value=""/>
</appSettings>
</configuration>

I try to save the foo value using the following method:

private void SaveValue(string value) {
    var config =
        ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    config.AppSettings.Settings.Add("foo", value);
    config.Save(ConfigurationSaveMode.Modified); 
}

but this not change the value of it. and I don't get a exception. how to fix this? thanks in advance!


回答1:


When you are debugging with Visual Studio probably the <yourexe>.vshost.exe.config is modified instead of the <yourexe>.exe.config. When you build the application in Release mode only the <yourexe>.exe.config exists and will be updated.

Your code will also add an extra node to the configuration file. Use something like the code below to update the setting:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["foo"].Value = "text";     
config.Save(ConfigurationSaveMode.Modified);



回答2:


App.config is copied to the output folder on build, named <yourexe>.exe.config. This is the actual configuration file that is loaded and saved on runtime.

Have a look in your output folder, there you will likely find that the configuration file contains your changes.




回答3:


Try by first deleting the old value and then add it again

 config.AppSettings.Settings.Remove("foo");
 config.AppSettings.Settings.Add("foo", value);
 config.Save(ConfigurationSaveMode.Modified);


来源:https://stackoverflow.com/questions/8840904/app-config-are-not-saving-the-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!