【问题标题】:Why does config.Appsettings.Settings["MySetting"].Value fail in Windows 7, but not other versions为什么 config.Appsettings.Settings["MySetting"].Value 在 Windows 7 中失败,但在其他版本中没有
【发布时间】:2011-12-01 01:43:06
【问题描述】:

我正在从 app.config 文件中读取设置,使用的代码与我在应用程序其他部分中使用的代码几乎相同。它在 WinXP 和 Win Server 2003 下运行良好,当我在 Windows 7 64 位下运行它时会产生异常:

System.NullReferenceException:对象引用未设置为对象的实例。

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 下运行良好。

我很困惑,因为这段代码在一个模块中工作,而不是在另一个模块中,并且不会产生构建错误。

【问题讨论】:

  • 这很可能是权限问题。用户无权写入 Program Files。你需要得到提升才能做到这一点(这可能不是一个好主意)。设置用户特定设置对您来说不够好吗?
  • 好吧,我实际上是在尝试从 app.config 中读取数据。用户组确实对该文件夹具有读取权限。在这种情况下,我认为这不是权利问题。它在另一个模块中工作正常,在同一文件夹中读取不同的 app.config。

标签: c# .net app-config


【解决方案1】:

System.Configuration.ConfigurationSettings 已弃用,适用于框架版本 1.0 和 1.1 的解决方案。

由于您使用的是 3.0,因此您应该使用 System.Configuration.ConfigurationManager。是一样的东西,用法一样

System.Configuration.ConfigurationManager["MsgAlertWav"];

hth,-covo

【讨论】:

    【解决方案2】:

    试试

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

    或者看看

    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-01
      • 2019-08-11
      • 1970-01-01
      • 1970-01-01
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      相关资源
      最近更新 更多