App Config Modification not reflected in code

断了今生、忘了曾经 提交于 2021-01-28 21:31:32

问题


I have a appsetting section in appconfig file as

<appSettings>    
  <add key="DayTime" value="08-20"/>
  <add key="NightTime" value="20-08"/>
</appSettings>

I am tyring to modify the app config while application is running. I changed key DayTime to 11-20 while application is running.

Now if I run this code again to fetch data from config, it shows previous set values.

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

Why it is so ?


回答1:


The reason behind why the AppSetting section in app.config file is not getting reflected during update in Run time is as follows:

  • When you add a new app.config file it actually creates a file in the local system.
  • When you compile it, actually it creates the necessary files including .Exe files in Debug/Release folder; depending upon the Build mode.
  • After successful build it also generates a .config file which looks like YourApplicationName.exe.config which holds the same entries in original app.config file. And the .Exe always refers to this file.
  • So whenever you edit the app.config at Runtime it actually updates the file but changes are not updated in YourApplicationName.exe.config file as it has not re-build yet.

So every time you need to re-build to your app to reflect the changes.




回答2:


I have my own answer. Just need to refresh appSettings section as

ConfigurationManager.RefreshSection("appSettings");



回答3:


app.config is cached, the changes will reflect when you restart the application. See is app.config file in WinForms cached by .Net framework?




回答4:


Try this:

string strDayTime = ConfigurationManager.AppSettings["DayTime"];

ConfigurationManager.AppSettings.Set("DayTime", "11-20");

strDayTime = ConfigurationManager.AppSettings["DayTime"];

The value of the strDayTime variables changes on both lines.



来源:https://stackoverflow.com/questions/16855043/app-config-modification-not-reflected-in-code

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