开发者

App.config only read when debugging

开发者 https://www.devze.com 2023-02-18 19:32 出处:网络
I am currently experiencing an issue that I haven\'t been able to resolve. I have an application where I have this code:

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.开发者_StackOverflow中文版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.


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);


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消