【问题标题】:Updating a value in a local app.config更新本地 app.config 中的值
【发布时间】:2011-11-08 14:37:27
【问题描述】:

我有一个 exe,它从其本地 app.config 文件中读取一些值:

TargetDate = ConfigurationManager.AppSettings.Get("ThresholdDate");

// and try to update with the current date
ConfigurationManager.AppSettings.Set("ThresholdDate", "2011-09-01");

我认为它曾经工作过,但现在根本没有看到 app.config 得到更新。

【问题讨论】:

标签: c# app-config


【解决方案1】:

我想你可以试试这样的:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
//change the config value
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

我不确定更改配置值的语法,但我之前做过Add,我知道你可以做一个删除,所以我想你可以像这样组合删除和添加:

config.AppSettings.Settings.Remove("ThresholdDate");
config.AppSettings.Settings.Add("ThresholdDate", "2011-09-01");

【讨论】:

  • 更改配置值的 C# 语法是什么?
  • 在那之后你是否进行了保存和刷新?
  • config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings");
  • 我可以保存值,然后右转并立即提取值,但是应用程序结束执行后它不会持续存在
  • 看起来它正在 .vshost.exe.config 而不是 app.config 中被更改,并且执行后该值不会保留
【解决方案2】:

看这里:How to change App.config file run time using C# 是答案 - 在 Visual Studio IDE 中运行时,您不会看到 /bin/appname.exe.config 中保留的值。您实际上必须进入 bin 目录并运行 exe。

所以这段代码实际上可以工作,只是不在调试模式下:

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

config.AppSettings.Settings["ThresholdDate"].Value = Convert.ToString(testdate);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

【讨论】:

  • 如果它解决了您的问题,您应该将此标记为您接受的答案(48 小时计时器现在应该过期)
【解决方案3】:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

config.AppSettings.Settings["ThresholdDate"].Value = Convert.ToString(testdate);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

这仅在您未处于调试模式时才有效。尝试在 /debug/appName.exe 中运行 yung 代码,您将看到 appName.exe.config 中的更改

干杯!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 2018-08-14
    • 1970-01-01
    • 2015-06-14
    • 2023-03-18
    • 2014-03-22
    • 2019-01-06
    相关资源
    最近更新 更多