我正在使用与我在应用程序其他部分中使用的代码几乎相同的代码从 app.config 文件中读取设置。它在 WinXP 和 Win Server 2003 下运行良好,当我在 Windows 7 64 位下运行它时它会生成异常:
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
这是简化的代码,但在 Windows 7 下会产生错误。它是为 32 位目标编译的 .NET 3.0 项目。我在另一个模块中有相同的代码,它在 Windows 7 下运行良好。
我很困惑,因为这段代码在一个模块中有效,但在另一个模块中无效,并且不会产生构建错误。
最佳答案
尝试
System.Configuration.ConfigurationSettings.AppSettings["MsgAlertWav"];
或者看看
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
关于c# - 为什么 config.Appsettings.Settings ["MySetting"].Value 在 Windows 7 中失败,但在其他版本中没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7654780/