App Config修改未反映在代码中

Raj*_*mar 1 c# app-config winforms

我在appconfig文件中有一个appsetting部分

<appSettings>    
  <add key="DayTime" value="08-20"/>
  <add key="NightTime" value="20-08"/>
</appSettings>
Run Code Online (Sandbox Code Playgroud)

我正忙着在应用程序运行时修改app配置.DayTime应用程序运行时,我将密钥更改为11-20.

现在,如果我再次运行此代码以从config获取数据,它将显示先前的设置值.

private void btnDayNightSettings_ShowingEditor(object sender, ItemCancelEventArgs e)
{
     string[] strDayTime = ConfigurationManager.AppSettings["DayTime"].Split('-');
}
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

Raj*_*mar 6

我有自己的答案。只需要刷新appSettings部分

ConfigurationManager.RefreshSection("appSettings");
Run Code Online (Sandbox Code Playgroud)


San*_*nda 5

在运行时更新期间没有反映AppSetting sectionin app.config文件的原因如下:

  • 当您添加新的app.config文件时,它实际上在本地系统中创建了一个文件.
  • 编译时,实际上它会创建必要的文件,包括.Exe文件Debug/Release夹中的文件; 取决于构建模式.
  • 成功构建后,它还会生成一个.config文件,该文件YourApplicationName.exe.config在原始app.config文件中保存相同的条目.而且.Exe总是指这个文件.
  • 因此,无论何时编辑app.configat Runtime,它实际上都会更新文件,但更改不会在YourApplicationName.exe.config文件中更新,因为它尚未重新构建.

因此,每次您需要重新构建应用程序以反映更改.