Configure a list of emails in app/web.config

Post date: Nov 20, 2009 7:55:16 AM

public enum MailType { To, CC } public class EmailElement : ConfigurationElement { [ConfigurationProperty("email", IsKey = true, IsRequired = true)] public string Email { get { return (string)this["email"]; } } [ConfigurationProperty("type", IsKey = false, IsRequired = false, DefaultValue=MailType.To)] public MailType Type { get { return (MailType)this["type"]; } } } public class EmailElementCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new EmailElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((EmailElement)element).Email; } public EmailElement this[int index] { get { return (EmailElement)BaseGet(index); } //set //{ // if (BaseGet(index) != null) // { // BaseRemoveAt(index); // } // BaseAdd(index, value); //} } } public class EmailConfigurationSection : ConfigurationSection { [ConfigurationProperty("emails")] public EmailElementCollection Emails { get { return (EmailElementCollection)this["emails"]; } } }

in app.config:

<configSections> <section name="MyApp.Emails" type="MyNamespace.EmailConfigurationSection, MyAssembly" requirePermission="false" /> </configSections> <MyApp.Emails> <emails> <!--<add email="peter@hotmail.com" type="To" />--> <add email="peter.henell@hotmail.com" type="To" /> </emails> </MyApp.Emails>

Use In code:

public static List<EmailElement> Emails

{ get { EmailConfigurationSection section = (EmailConfigurationSection)ConfigurationManager.GetSection("MyApp.Emails"); foreach (var item in section.Emails) { Console.WriteLine(((EmailElement)item).Email); } return null; } }