kfuglsang
kfuglsang

Reputation: 2505

App.config only read when debugging

I am currently experiencing an issue that I haven't been able to resolve.

I have an application where I have this code:

AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", "App.config");
AppDomain.CurrentDomain.SetupInformation.ConfigurationFile = Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location, "App.config");
MessageBox.Show(ConfigurationSettings.AppSettings.Count.ToString());

The configuration file is indeed called App.config in the application folder (I am doing this because I have two applications reading/modifying the same config file).

When I start either of them through the Visual Studio Debugger, it correctly tells me that I have 11 appsettings. However, when run outside of the debugger, I get 0.

What might be wrong here? I am 100% sure that this code has worked in the past.

Upvotes: 0

Views: 489

Answers (2)

Dan Waterbly
Dan Waterbly

Reputation: 850

It looks like you are not passing the correct path to App.Config. Try this instead:

AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", "App.config");
AppDomain.CurrentDomain.SetupInformation.ConfigurationFile = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "App.config"); 
MessageBox.Show(ConfigurationSettings.AppSettings.Count.ToString());

Notice the call to Path.GetDirectoryName(). Your code is getting the location to the exe file, and is then appending "App.Config" to it, which is resolving to a file that does not exist.

Upvotes: 0

kfuglsang
kfuglsang

Reputation: 2505

I was finally able to solve it myself right now. The solution is to access the configuration settings through

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

Upvotes: 1

Related Questions