Why does config.Appsettings.Settings[“MySetting”].Value fail in Windows 7, but not other versions

夙愿已清 提交于 2019-12-11 00:20:03

问题


I'm reading a setting out of the app.config file using code nearly identical to that which I've used in other portions of the app. It works fine under WinXP and Win Server 2003, when I run it under Windows 7 64-bit it generates an exception:

System.NullReferenceException: Object reference not set to an instance of an object.

string exePath = System.IO.Path.Combine(Environment.CurrentDirectory, applicationName);

// Get the configuration file. The file name has this format appname.exe.config.

System.Configuration.Configuration utilConfig = ConfigurationManager.OpenExeConfiguration(exePath);
string fileName = utilConfig.AppSettings.Settings["MsgAlertWav"].Value; //<<Fails here

This is simplified code, but generates the error under Windows 7. It's a .NET 3.0 project compiled for 32-bit target. I have this same code in another module and it works fine under Windows 7.

I am mystified since this code works in one module, but not another and generates no build errors.


回答1:


Try with

System.Configuration.ConfigurationSettings.AppSettings["MsgAlertWav"];

or have a look at the

Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)



回答2:


System.Configuration.ConfigurationSettings is deprecated and is meant for solutions on framework versions 1.0 and 1.1.

Since you are using a 3.0 you should be using System.Configuration.ConfigurationManager. Is pretty mcuh the same thing, has the same usage

System.Configuration.ConfigurationManager["MsgAlertWav"];

hth, -covo



来源:https://stackoverflow.com/questions/7654780/why-does-config-appsettings-settingsmysetting-value-fail-in-windows-7-but-n

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