views:

1452

answers:

2

Hi,

Could someone tell me the advantages to using the ConfigurationManager class which load's a config file for manipulation VS an XML file with a class you build to read it yourself?

Recently, I built a class which inherits from ConfigurationSection in order to manipulate a custom section within app.config. This was quite a bit of work compared to just opening and reading an XML file.

Some people chose the first approach, others chose the second.

What's good practice?

+1  A: 

It's just a recommended and easier way of reading and writing data to configuration files. Using XML DOM is too low level.

You can always get raw xml configuration from ConfigurationSection using section.SectionInformation.GetRawXml() if needed. Likewise use SetRawXml to set this.

There are a few gotchas though when using ConfigurationManager, for example when you load a config file using OpenMappedExeConfiguration, you get an in memory configuration which is "merged" and has sections from machine.config. You can check if a section came from the file you provided using section.ElementInformation.Source.Equals(source.FilePath).

Reference: MSDN

Koistya Navin
+1  A: 

This is an old question, but what the hell... so yes, there is quite some code overhead in writing configuration sections and elements, but what you get as compared to using your own class with an XML serializer include:

  • Type conversions and validations: if one of your configuration settings is, say, a "Type" (maybe you store in your configuration what kind of implementation you need to create for some provider), then the ConfigurationManager will not only convert whatever was written in the .config file to a System.Type, but you can also add validation attribtues on your ConfigurationElement's property, like "SubclassTypeValidatorAttribute", which will check that the given type derives from your base provider class/interface. You can of course add your own validators, so that in the rest of your code, you just "get" the configuration and you know everything's valid.
  • Multi-level settings hierarchy: you can play around with storing settings at the machine, application or user levels, which gives you a mechanism to handle default vs. user-specific settings. You also have APIs to load configurations from custom locations.
  • No duplication in config files: if you're using other .NET features like TraceSources and stuff, the configuration for that is already in the .config file (say you're troubleshooting a problem and you want to turn on some debug trace that's off by default... you do that by just modifying the .config). If you're using your own config file for your custom settings, then you end up with 2 configuration files, which is not so good.

There's probably other benefits, but that's what comes to mind so far.

Ludovic