c# – ConfigurationSection ConfigurationManager.GetSection()始终返回null

我正在尝试学习如何使用ConfigurationSection类.我曾经使用IConfigurationSectionHandler,但发布它已被贬值.所以成为一个好小伙子,我正在尝试“正确”的方式.我的问题是它总是返回null.

我有一个控制台应用程序和一个DLL.

class Program
{
    static void Main(string[] args)
    {           
        StandardConfigSectionHandler section = StandardConfigSectionHandler.GetConfiguration();

        string value = section.Value;
    }
}

应用配置:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configSections>
    <sectionGroup name="ConfigSectionGroup">
      <section name="ConfigSection" type="Controller.StandardConfigSectionHandler,Controller" />
    </sectionGroup>
  </configSections>

  <ConfigSectionGroup>
    <ConfigSection>
      <test value="1" />
    </ConfigSection>
  </ConfigSectionGroup>

</configuration>

DLL中的section handler:

namespace Controller
{    
    public class StandardConfigSectionHandler : ConfigurationSection
    {
    private const string ConfigPath = "ConfigSectionGroup/ConfigSection/";

    public static StandardConfigSectionHandler GetConfiguration()
    {
        object section = ConfigurationManager.GetSection(ConfigPath);
        return section as StandardWcfConfigSectionHandler;
    }

    [ConfigurationProperty("value")]
    public string Value
    {
        get { return (string)this["value"]; }
        set { this["value"] = value; }
    }
  }
}

有什么值得我尝试的“ConfigPath”它将返回null,或者抛出一个错误,说“test”是一个无法识别的元素.我试过的价值:

> ConfigSectionGroup
> ConfigSectionGroup /
> ConfigSectionGroup / ConfigSection
> ConfigSectionGroup / ConfigSection /
> ConfigSectionGroup / ConfigSection / test
> ConfigSectionGroup / ConfigSection / test /

解决方法

你的代码有几个错误.

>你总是在你的GetConfiguration方法中返回null,但是我将假设这只是在问题中,而不是在你的实际代码中.
>更重要的是,ConfigPath值的格式不正确.您有一个尾部斜杠ConfigSectionGroup / ConfigSection /,删除最后一个斜杠,它将能够找到该部分.
>最重要的是,您声明部分的配置系统将会将您的“值”存储在ConfigSection元素的属性中.喜欢这个

<ConfigSectionGroup>
  <ConfigSection value="foo" />
</ConfigSectionGroup>

所以,把它放在一起:

public class StandardConfigSectionHandler : ConfigurationSection
{
    private const string ConfigPath = "ConfigSectionGroup/ConfigSection";

    public static StandardConfigSectionHandler GetConfiguration()
    {
        return (StandardConfigSectionHandler)ConfigurationManager.GetSection(ConfigPath);
    }

    [ConfigurationProperty("value")]
    public string Value
    {
        get { return (string)this["value"]; }
        set { this["value"] = value; }
    }
}

要了解有关如何配置配置部分的更多信息,请参阅这个出色的MSDN文档:How to: Create Custom Configuration Sections Using ConfigurationSection.它还包含有关如何将配置值存储在(像您的测试元素)的子元素中的信息.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...