Search code examples
c#wpfconfigurationmanager

ConfigurationManager: always key-value pairs?


I try to use ConfigurationManager to configure my c# app. Is it always so, that CM only does key-value pairs? like with

 <add key="k1" value="v1"/>

or can I also use items like

 <God Name="Shiva" Spouse="Parvati" Legs="2 Arms="6"/>

Solution

  • There are custom configuration sections that you can use: https://learn.microsoft.com/en-us/dotnet/api/system.configuration.configurationsection?view=dotnet-plat-ext-5.0

    Replace CustomSection with God and you're set. You need to write the extra code to read them if course, but it's totally doable.

    <?xml version="1.0" encoding="utf-8"?>
     <configuration>  
       <configSections>
         <section name="CustomSection" type="Samples.AspNet. CustomSection, CustomConfigurationSection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" restartOnExternalChanges="true" />
       </configSections>  
    
       <CustomSection fileName="default.txt" maxUsers="1000" maxIdleTime="00:15:00" /> 
    
     </configuration>
    

    Another excellent example can be found here: https://www.jokecamp.com/blog/net-custom-configuration-section-collection-and-elements/

    Beware though. Configuration should be used for application constants. God's and their abilities look like a better fit for a data source (though I guess it was just an example).