How to use a custom section handler without implementing the IConfigurationSectionHandler interface?

1.5k views Asked by At

I would like to create a section in my web.config file like this:

<paths>
                <path>\\123.123.132.123\c$\test\folder</path>
                <path>\\123.123.132.123\c$\test\folder</path>
</paths>

I am searching for alternatives, I would like to use one of the default section handlers, but I could only find section handlers that would work with this config

<CustomGroup>
        <add key="key1" value="value1"/>
</CustomGroup>

(that would be SingleTagSectionHandlers, DictionarySectionHandlers, NameValueSectionHandler and so on).

Is there any way that I substitute the < add> tag for a < path> tag? Or do I have to implement the IConfigurationSectionHandler interface?

1

There are 1 answers

3
Erik Philips On BEST ANSWER

do I have to implement the IConfigurationSectionHandler interface?

You don't have to if you use the System.Configuration.IgnoreSectionHandler.

web.config

<configuration>
  <configSections>
    <section name="Paths" type="System.Configuration.IgnoreSectionHandler" />
  </configSections>
  <Paths>
    <path>\\123.123.132.123\c$\test\folder</path>
    <path>\\123.123.132.123\c$\test\folder</path>
  </Paths>

Then you can manually read the web.config with whatever you want to get your values.

public IEnumerable<string> GetPathsFromConfig()
{
  var xdoc = XDocument.Load(ConfigurationManager
    .OpenExeConfiguration(ConfigurationUserLevel.None)
    .FilePath);

  var paths = xdoc.Descendants("Paths")
    .Descendants("path")
    .Select(x => x.Value);

  return paths
}

Other wise you'll have to Create Custom Configuration Sections Using ConfigurationSection (how-to).