If you are one of those who love to separate your code throughout different projects in a solution, you probably will need to share the same App.config for multiple projects.
By default the Visual Studio build process will rename your configuration file from App.config to <ApplicationName>.exe.config , you are able to change the name but you won’t be able to read the configurations.
In my case I wanted to be able to read and update the configuration file from a Windows App and then used by a Windows Service App.
Initial solution setup:
1 2 3 4 5 |
Solution Windows Form Project App.config Windows Service Project App.config |
Initial App.config for both projects:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?xml version="1.0" encoding="utf-8"?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <appSettings> <add key="settingName1" value="" /> <add key="settingName1" value="" /> </appSettings> <connectionStrings> <add name="myConnection1" connectionString="" providerName="System.Data.SqlClient" /> <add name="myConnection2" connectionString="" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration> |
We are going to use an external file to store the appSettings and ConnectionStrings parameters, final App.config for both projects will look like this:
1 2 3 4 5 6 7 8 9 10 |
<?xml version="1.0" encoding="utf-8"?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <appSettings configSource="AppSettings.config"></appSettings> <connectionStrings configSource="ConnectionStrings.config"></connectionStrings> </configuration> |
AppSettings.config and ConnectionStrings.config files:
1 2 3 4 |
<appSettings> <add key="settingName1" value="" /> <add key="settingName1" value="" /> </appSettings> |
1 2 3 4 |
<connectionStrings> <add name="myConnection1" connectionString="" providerName="System.Data.SqlClient" /> <add name="myConnection2" connectionString="" providerName="System.Data.SqlClient" /> </connectionStrings> |
Final solution structure:
1 2 3 4 5 6 7 8 9 |
Solution Windows Form Project App.config AppSettings.config ConnectionStrings.config Windows Service Project App.config AppSettings.config ConnectionStrings.config |