Help using ConfigurationSection to read correctly from the configuration file

I'm trying to create classes to read from my configuration file using ConfigurationSection and ConfigurationElementCollection, but it's hard for me.

As an example configuration:

<PaymentMethodSettings> <PaymentMethods> <PaymentMethod name="blah blah" code="1"/> <PaymentMethod name="blah blah" code="42"/> <PaymentMethod name="blah blah" code="43"/> <Paymentmethod name="Base blah"> <SubPaymentMethod name="blah blah" code="18"/> <SubPaymentMethod name="blah blah" code="28"/> <SubPaymentMethod name="blah blah" code="38"/> </Paymentmethod> </PaymentMethods> </PaymentMethodSettings> 
+4
source share
2 answers

The magic here is to use ConfigurationSection classes.

These classes simply should contain properties corresponding to 1: 1, with your configuration scheme. You use attributes to let .NET know which properties correspond to those elements.

So you can create a PaymentMethod and inherit it from ConfigurationSection

And you must create a SubPaymentMethod and inherit it from ConfigurationElement.

PaymentMethod will have a ConfigurationElementCollection SubPaymentMethods in it as a property, that is, how you connect complex types together.

You do not need to write your own XML syntax code.

 public class PaymentSection : ConfigurationSection { // Simple One [ConfigurationProperty("name")]] public String name { get { return this["name"]; } set { this["name"] = value; } } } 

etc...

See here how to create a ConfigurationElementCollections so you can have nested types:

http://blogs.neudesic.com/blogs/jason_jung/archive/2006/08/08/208.aspx

+5
source

This should help you understand how to create configuration sections correctly and then read from them.

+3
source

All Articles