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.

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

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

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

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 <