C# XML 配置文件自定义部分始终为空

C# XML config file custom section always null

正在处理 VSTO Outlook 插件。我需要将配置参数存储在 XML 文件中。我正在努力解决一些基本的配置文件加载问题。我希望有新的观点:

customConfiguration.xml

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

  <configSections>
      <section name="CDSSettings"  type="System.Configuration.NameValueSectionHandler" />
  </configSections>

  <CDSSettings>
    <add key="APIusername" value="myUser" />
    <add key="APIpassword" value="myPassword" />
  </CDSSettings>

    <appSettings>
      <add key="logLevel" value="0" /> 
  </appSettings>
</configuration>

代码

ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = "customConfiguration.xml";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

AppSettingsSection appSettingsSection = (config.GetSection("appSettings") as AppSettingsSection);
// --> All ok

ConfigurationSection CDSSettings = (ConfigurationSection)config.GetSection("CDSSettings");
// --> How to get the APIusername key?

我是否有机会避免使用 XML 解析器或 SectionInformation.GetRawXml()?

无法解释为什么 ConfigurationManager.GetSectionconfig.GetSection returns 不同的结果 object,在第一种情况下可以转换为 NameValueCollection,和部分即 DefaultSection in second

我建议创建一个自定义部分并使用它:

public class CDSSettings : ConfigurationSection
{
    [ConfigurationProperty("MyValues")]
    public KeyValueConfigurationCollection MyValues
    {
        get { return (KeyValueConfigurationCollection) this["MyValues"]; }
        set { this["MyValues"] = value; }
    }
}

配置看起来像

<section name="CDSSettings"  type="UCAddin.CDSSettings, UCAddin" />
...
<CDSSettings>
  <MyValues>
    <add key="APIusername" value="myUser" />
    <add key="APIpassword" value="myPassword" />
  </MyValues>
</CDSSettings>

检索代码:

var CDSSettings = (CDSSettings)config.GetSection("CDSSettings");

更多 在自定义部分的情况下,您还可以指定不同类型的字段,例如 你可以有单独的命名元素:

public class Credentials : ConfigurationElement
{
    [ConfigurationProperty("login")]
    public string Login
    {
        get { return (string)this["login"]; }
        set { this["login"] = value; }
    }
}

具有命名属性

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

配置看起来像

<CDSSettings>
  <credentials login="testlogin" />
</CDSSettings>

检查 this MSDN article 以获得更多可能性

作为 AppSettings 您可以将 属性 注册为默认集合

public class CDSSettings : ConfigurationSection
{

    [ConfigurationProperty("", IsDefaultCollection = true)]
    public KeyValueConfigurationCollection MyValues => 
                (KeyValueConfigurationCollection) this[string.Empty];
}

并具有应用设置中的参数

<CDSSettings>
  <add key="login" value="User" />
</CDSSettings>

但是在代码中,这些数据可以从 属性 访问(如果您不在 class 中实现索引器)

var settings = (CDSSettings)config.GetSection("CDSSettings");
settings.MyValues