c# - Custom app.config section with a simple list of "add" elements -
how create custom app.config section simple list of add
elements?
i have found few examples (e.g. how create custom config section in app.config?) custom sections this:
<registercompanies> <companies> <company name="tata motors" code="tata"/> <company name="honda motors" code="honda"/> </companies> </registercompanies>
but how avoid collection element ("companies") looks same appsettings
, connectionstrings
sections? in other words, i'd like:
<registercompanies> <add name="tata motors" code="tata"/> <add name="honda motors" code="honda"/> </registercompanies>
full example code based on op config file:
<configuration> <configsections> <section name="registercompanies" type="my.myconfigsection, my.assembly" /> </configsections> <registercompanies> <add name="tata motors" code="tata"/> <add name="honda motors" code="honda"/> </registercompanies> </configuration>
here sample code implement custom config section collapsed collection
using system.configuration; namespace { public class myconfigsection : configurationsection { [configurationproperty("", isrequired = true, isdefaultcollection = true)] public myconfiginstancecollection instances { { return (myconfiginstancecollection)this[""]; } set { this[""] = value; } } } public class myconfiginstancecollection : configurationelementcollection { protected override configurationelement createnewelement() { return new myconfiginstanceelement(); } protected override object getelementkey(configurationelement element) { //set whatever element property want use key return ((myconfiginstanceelement)element).name; } } public class myconfiginstanceelement : configurationelement { //make sure set iskey=true property exposed getelementkey above [configurationproperty("name", iskey = true, isrequired = true)] public string name { { return (string) base["name"]; } set { base["name"] = value; } } [configurationproperty("code", isrequired = true)] public string code { { return (string) base["code"]; } set { base["code"] = value; } } } }
here example of how access configuration information code.
var config = configurationmanager.getsection("registercompanies") myconfigsection; console.writeline(config["tata motors"].code); foreach (var e in config.instances) { console.writeline("name: {0}, code: {1}", e.name, e.code); }
Comments
Post a Comment