Title: ASP.NET: Split AppSettings and ConnectionStrings to separate files
Slug: asp-net-split-appsettings-and-connectionstrings-to-separate-files
Date: 2009-09-28 16:24:00
Author: Kartones
Lang: en
Tags: Development, ASP.NET, Patterns & Practices
Description: How to split app settings and connection strings in ASP.NET to separate files, allowing for easier management and organization of configuration settings.

<p>This is a simple yet not always known "trick".</p>  <p>We usually have in our ASP.NET Web.Config files the app settings variables and connection strings:</p>
<pre class="code">&lt;appSettings&gt;
&lt;add key="MyAppSetting1" value="" /&gt;
&lt;add key="MyAppSetting2" value="" /&gt;
&lt;add key="MyAppSetting3" value="" /&gt;
&lt;/appSettings&gt;
&lt;connectionStrings&gt;
&lt;add name="Conn1" connectionString="xxx" providerName="System.Data.SqlClient"/&gt;
&lt;add name="Conn2" connectionString="xxx" providerName="System.Data.SqlClient"/&gt;
&lt;/connectionStrings&gt;</pre><p>What is not so commonly known is that you can split both sections, using special attributes on the nodes:</p><pre class="code">&lt;appSettings <b>file="AppSettings.config"</b>&gt;
&lt;add key="MyAppSetting1" value="" /&gt;
&lt;add key="MyAppSetting2" value="" /&gt;
&lt;/appSettings&gt;
&lt;connectionStrings <b>configSource="ConnectionStrings.config"</b> /&gt;</pre><p>The &lt;appSettings&gt; node can have some or all keys in another file, like this AppSettings.config sample file:</p><pre class="code">&lt;appSettings&gt;
&lt;add key="MyAppSetting2" value="" /&gt;
&lt;add key="MyAppSetting3" value="" /&gt;
&lt;/appSettings&gt;</pre>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. <p> </p><p>With the &lt;connectionStrings&gt; node we can take out all conn strings (beware, you can't split between the two, if you specify a configSource then <b>all</b> must go on that file):</p><pre class="code">&lt;connectionStrings&gt;
&lt;add name="Conn1" connectionString="xxx" providerName="System.Data.SqlClient"/&gt;
&lt;add name="Conn2" connectionString="xxx" providerName="System.Data.SqlClient"/&gt;&lt;/connectionStrings&gt;</pre><p> </p><p><b>Note</b>: Both AppSettings.config and ConnectionStrings.config must <b>only</b> contain &lt;appSettings&gt; and &lt;connectionStrings&gt; as the root XML nodes. Do not place any other xml tag (not even the &lt;?xml version="1.0"?&gt; definition tag). </p>
