Tuesday, February 23, 2021

ASP.NET/C#: Link a config file to web.config for an extra app-Settings section


Multiple appSettings sections are not allowed in web.config. However, we can add config sections by using <configSections>.

In web.config, add <configSections> at the very beginning of <configuration> element.

<configuration>
    <configSections>
        <section name="appSettingsExtra" type="System.Configuration.NameValueFileSectionHandler, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
    </configSections>
    <
appSettingsExtra configSource="webextra.config">
    </
appSettingsExtra>
    ....
</configuration>


Create a new file webextra.config with the following content:

<appSettingsExtra>
     <add key="TheKey" value="TheValue"/>
</appSettingsExtra>


In the code, to read the parameter from webextra.config:

System.Collections.Specialized.NameValueCollection extraSettings = (System.Collections.Specialized.NameValueCollection)ConfigurationManager.GetSection("appSettingsExtra");
string value = extraSettings["TheKey"];



No comments:

 
Get This <