【问题标题】:app.config are not saving the valuesapp.config 没有保存值
【发布时间】:2012-02-09 02:03:38
【问题描述】:
我的App.Config 类似于:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="foo" value=""/>
</appSettings>
</configuration>
我尝试使用以下方法保存foo 值:
private void SaveValue(string value) {
var config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Add("foo", value);
config.Save(ConfigurationSaveMode.Modified);
}
但这不会改变它的价值。我没有例外。
如何解决这个问题?提前致谢!
【问题讨论】:
标签:
c#
.net
xml
app-config
【解决方案1】:
当您使用 Visual Studio 进行调试时,<yourexe>.vshost.exe.config 可能会被修改,而不是 <yourexe>.exe.config。当您在发布模式下构建应用程序时,只有 <yourexe>.exe.config 存在并将被更新。
您的代码还将在配置文件中添加一个额外的节点。使用类似下面的代码来更新设置:
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["foo"].Value = "text";
config.Save(ConfigurationSaveMode.Modified);
【解决方案2】:
App.config 在构建时被复制到名为<yourexe>.exe.config 的输出文件夹中。这是在运行时加载和保存的实际配置文件。
查看您的输出文件夹,您可能会发现配置文件包含您的更改。
【解决方案3】:
尝试先删除旧值,然后重新添加
config.AppSettings.Settings.Remove("foo");
config.AppSettings.Settings.Add("foo", value);
config.Save(ConfigurationSaveMode.Modified);