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

StackOverflow https://stackoverflow.com/questions/18621863

  •  27-06-2022
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top