Why my changes of AppSettings in App.config is not taken into account in run-time? (Console Application)

有些话、适合烂在心里 提交于 2019-11-27 13:13:07

问题


I have a console application which has its own App.config.

I need to change some values in section time to time.

My problem is, when I execute the exe within the bin/debug folder it gets the relevant appsettings correctly. But when I edit and change values of some key/value pairs and RE-RUN the exe, it still reads the original values.

(By RE-RUN I mean running the application on the command promt by calling MyTool.exe)

I tried to call

ConfigurationManager.RefreshSection("appSettings");

in the begining of my Main method. But did not help.

Can you please advise? Thanks


回答1:


But when I edit and change values of some key/value pairs and RE-RUN the exe, it still reads the original values.

Depends how you are RE-RUNNing this exe. If you are doing this in Visual Studio, by hitting F5, VS simply copies the app.config file in your project to the output and renames it to AppName.exe.config. So if you want your changes to be taken into account you have to modify AppName.exe.config (not App.config) and then run the executable from the Windows Explorer.

This being said, the App.config is read and parsed only once. When the application starts. The values are then cached to avoid expensive XML parsing everytime your application requests some value.

App.config is designed to store configuration values that are not supposed to be changed. If you need to change configuration values dynamically you should use some other storage mechanism: file, database, ...

But the ConfigurationManager.RefreshSection("appSettings"); method should work. Once you have modified the AppName.exe.config file, you call this method and then refetch the value you need using ConfigurationManager.AppSettings["someKey"]; which should return you the new value.




回答2:


  Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// change ConnectionString in App.Config for Entity FrameWork Object....
 //..... 
config.Save();

are you save config file?



来源:https://stackoverflow.com/questions/11466965/why-my-changes-of-appsettings-in-app-config-is-not-taken-into-account-in-run-tim

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