Search code examples
c#.netxmlapp-config

How to retrieve a custom section from an app.config in .NET?


I have a .NET Framework 4.7.2 library project, inside there's an App.config file like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="NewDocumentMetadata" type="System.Configuration.NameValueSectionHandler" />
    </configSections>
    <NewDocumentMetadata>
        <add key="Type" value="principal"/>
        <add key="IsActive" value="true"/>
    </NewDocumentMetadata>
    <appSettings>
        <add key="Entity" value="9"/>
        <add key="Flux" value="pdf"/>
    </appSettings>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <!-- [...] -->
        </assemblyBinding>
    </runtime>
</configuration>

As you can see, I have some standard settings, but also a custom section. I have no problems with the settings, but when I retrieve the section, it works, but there I'm stuck, when I try to cast it to NameValueCollection or AppSettingsSection it gives me a null value, I'm stuck with a ConfigurationOption object I am not able to work with.

        var appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);

        flux = appConfig.AppSettings.Settings["Flux"].Value; //Works
        entity = appConfig.AppSettings.Settings["Entity"].Value; //Works

        var metadataSection = appConfig.GetSection("NewDocumentMetadata"); //What do I do with this boy?

I need to retrieve the settings within the NewDocumentMetadata section, how to proceed?


Solution

  • I just found out that the problem was with this line :

    <section name="NewDocumentMetadata"        
             type="System.Configuration.NameValueSectionHandler" />
    

    I changed the type and went for this :

    <section name="NewDocumentMetadata"  
             type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
    

    Now I just have to do this kind of code to retrieve the values I want:

    var metadataSection = (AppSettingsSection)appConfig.GetSection("NewDocumentMetadata");
    
    foreach (var key in metadataSection.Settings.AllKeys)
    {
        string value = metadataSection.Settings[key].Value;
    }