嵌套配置部分app.config

我没有找到如何在app.config中访问这样的嵌套配置部分的任何示例

           

我之前使用过ConfigurationElementCollection和ConfigurationElement。 但我不知道怎么做以上?

你需要:

my.configuration定义为section group,将emailNotification定义为组内的一个部分。 在配置文件中添加以下内容:

   

实现配置节组( my.configuration )。

 public class MyConfigurationGroup : ConfigurationSectionGroup { [ConfigurationProperty( "emailNotification" )] public EmailNotificationSection EmailNotification { get { return (EmailNotificationSection)base.Sections[ "emailNotification" ]; } } } 

实现配置部分( emailNotification )。

 public class EmailNotificationSection : ConfigurationSection { [ConfigurationProperty( "to" )] public ValueElement To { get { return (ValueElement)base[ "to" ]; } } [ConfigurationProperty( "from" )] public ValueElement From { get { return (ValueElement)base[ "from" ]; } } [ConfigurationProperty( "subject" )] public ValueElement Subject { get { return (ValueElement)base[ "subject" ]; } } [ConfigurationProperty( "smtpHost" )] public ValueElement SmtpHost { get { return (ValueElement)base[ "smtpHost" ]; } } [ConfigurationProperty( "triggers" )] public TriggerElementCollection Triggers { get { return (TriggerElementCollection)base[ "triggers" ]; } } } 

实现必要的配置元素和配置元素集合。

 public class ValueElement : ConfigurationElement { [ConfigurationProperty( "value" )] public string Value { get { return (string)base[ "value" ]; } set { base[ "value" ] = value; } } } public class TriggerElement : ConfigurationElement { [ConfigurationProperty( "name" )] public string Name { get { return (string)base[ "name" ]; } set { base[ "name" ] = value; } } [ConfigurationProperty( "varAlias" )] public string VarAlias { get { return (string)base[ "varAlias" ]; } set { base[ "varAlias" ] = value; } } [ConfigurationProperty( "lower" )] public int Lower { get { return (int)base[ "lower" ]; } set { base[ "lower" ] = value; } } [ConfigurationProperty( "upper" )] public int Upper { get { return (int)base[ "upper" ]; } set { base[ "upper" ] = value; } } } [ConfigurationCollection( typeof( TriggerElement ) )] public class TriggerElementCollection : ConfigurationElementCollection { public TriggerElement this[ string name ] { get { return (TriggerElement)base.BaseGet( name ); } } public TriggerElement this[ int index ] { get { return (TriggerElement)base.BaseGet( index ); } } protected override ConfigurationElement CreateNewElement() { return new TriggerElement(); } protected override object GetElementKey( ConfigurationElement element ) { return ( (TriggerElement)element ).Name; } } 

更新配置文件并实现必要的配置位后,您可以按如下方式访问您的部分:

 Configuration config = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None ); MyConfigurationGroup myConfiguration = (MyConfigurationGroup)config.GetSectionGroup( "my.configuration" ); EmailNotificationSection section = myConfiguration.EmailNotification;