ASP.NET: Split AppSettings and ConnectionStrings to separate files

This is a simple yet not always known "trick".

We usually have in our ASP.NET Web.Config files the app settings variables and connection strings:

<appSettings>
<add key="MyAppSetting1" value="" />
<add key="MyAppSetting2" value="" />
<add key="MyAppSetting3" value="" />
</appSettings>
<connectionStrings>
<add name="Conn1" connectionString="xxx" providerName="System.Data.SqlClient"/>
<add name="Conn2" connectionString="xxx" providerName="System.Data.SqlClient"/>
</connectionStrings>

What is not so commonly known is that you can split both sections, using special attributes on the nodes:

<appSettings file="AppSettings.config">
<add key="MyAppSetting1" value="" />
<add key="MyAppSetting2" value="" />
</appSettings>
<connectionStrings configSource="ConnectionStrings.config" />

The <appSettings> node can have some or all keys in another file, like this AppSettings.config sample file:

<appSettings>
<add key="MyAppSetting2" value="" />
<add key="MyAppSetting3" value="" />
</appSettings>

Now, we would end having the same 3 keys as in the original web.config file, but MyAppSetting2 would be overwritten in AppSettings.config and MyAppSetting3 would be created in the same file.

With the <connectionStrings> node we can take out all conn strings (beware, you can't split between the two, if you specify a configSource then all must go on that file):

<connectionStrings>
<add name="Conn1" connectionString="xxx" providerName="System.Data.SqlClient"/>
<add name="Conn2" connectionString="xxx" providerName="System.Data.SqlClient"/></connectionStrings>

Note: Both AppSettings.config and ConnectionStrings.config must only contain <appSettings> and <connectionStrings> as the root XML nodes. Do not place any other xml tag (not even the <?xml version="1.0"?> definition tag).

ASP.NET: Split AppSettings and ConnectionStrings to separate files published @ . Author: