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

pencilCake picture pencilCake · Jul 13, 2012 · Viewed 28.5k times · Source

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

Answer

Darin Dimitrov picture Darin Dimitrov · Jul 13, 2012

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.