【问题标题】:ConfigurationManager.GetSection returns nullConfigurationManager.GetSection 返回 null
【发布时间】:2012-08-06 01:44:38
【问题描述】:

这是我的 app.config

<configuration>
  <configSections>
      <section name="procedureList" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.30319, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
  </configSections>

  <procedureList>
    <add key="NAS.spBusObjGetLineProd" value="@area='Melt Shop';@endDt=?date?;@dayonly=1;@obj='Melt Shop Business Objective" />
    <add key="NAS.spBusObjGetLineProd" value="@area='Cold Mill';@endDt=?date?;@dayonly=1;@obj='Cold Mill Business Objective" /> 
  </procedureList>
  <appSettings>
    <add key="Connstr" value=""/>
    <add key="Userid" value=""/>
    <add key="Timeout" value=""/>
  </appSettings>

</configuration>

但是当我在代码中调用它时,我得到一个空值

public void samplemethod()
{
    NameValueCollection nvc = ConfigurationManager.GetSection("procedureList") as NameValueCollection;
    string[] keys = nvc.AllKeys;
}

如果有任何帮助指出我做错了什么,我将不胜感激

【问题讨论】:

  • 你投错了。我将在下面发布一个示例以及可以用作参考的链接
  • 如果as 转换操作失败,则返回空值。但是,配置文件指出节类型是NameValueSectionHandler——在调用 GetSection() 时应该强制转换为这种类型。
  • 即使我将类型更改为 NameValueSectionHandler,我仍然得到一个空返回
  • 放置断点时nvc的值是多少..?
  • 只是想看看会发生什么,我刚刚返回了一个对象,如下所示,但仍然为空。 object nvc = ConfigurationManager.GetSection("procedureList");

标签: c# app-config


【解决方案1】:

使用即时窗口检查它指向的配置文件。就我而言,我有 app.config 我希望它可以读取,但是使用命令。 ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) 它指向其他类似 nuintrunner.exe.config 的信息,因为该信息已加载到 bin 中。这有助于加载正确的配置文件

【讨论】:

    【解决方案2】:

    如果您正在测试您的课程,您必须将配置复制到您的测试项目中的app.config

    【讨论】:

      【解决方案3】:

      Using section handlers to group settings in the configuration file

      例如,您可以按照以下方式进行操作

      private void ReadSettings()
      {
          NameValueCollection loc = 
         (NameValueCollection )ConfigurationSettings.GetConfig("procedureList");
      }
      

      MSDN ConfigurationManager.GetConfig Method

      【讨论】:

      • 弄明白了。我在 dll 中有应用程序配置,而不是调用表单。因为最终 dll 将被服务调用,所以我需要使用 ConfigurationManager.OpenExeConfiguration 来修复它。谢谢你的鼓励。
      • 没问题..这就是为什么我总是问开发人员是否调试他们的代码..调试器是一个很棒的工具...很高兴你让它工作
      • 你试过了吗:NameValueCollection nvc = (NameValueCollection)ConfigurationManager.GetSection("procedureList");?我建议这样做,因为 ConfigurationSettings.GetConfig 现在 已过时 :/
      • 好的等等,只是本地错误。总有一天会死的。基本数据在本地会更好。
      • 我举了一个例子,不知道你为什么投了反对票,但一切都很好......干杯
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-28
      • 1970-01-01
      • 2020-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      相关资源
      最近更新 更多