I use different settings for my application when it is running on the live server and when it is running on my development machine. To manage this I name my config files using the target name like so:

  • Web.Debug.config
  • Web.Release.config

Adding the following to the project file will cause MSBuild to automatically copy the correct file to ‘Web.config’ when you build the project in Visual Studio. In my case the ‘BeforeBuild’ target was already in the project file but commented out, I just needed to add the copy task and related items.

<Target Name="BeforeBuild">
   <ItemGroup>
   <ConfigSourceFiles Include="Web.$(Configuration).config" />
   <ConfigDestinationFiles Include="Web.config" />
   </ItemGroup>
   <Copy
      SourceFiles="@(ConfigSourceFiles)"
      DestinationFiles="@(ConfigDestinationFiles)"
   />
</Target>

So I select the right target from the toolbar and build/publish and the correct settings are used.

Where possible, to avoid duplicating settings, I create separate config files and point the main config files at it using the configSource attribute. For example the page settings for debug and release are the same so my pages element in both files look like this:

   <pages configSource="Configuration\System.Web\pages.config" />

Before implementing this I was manually changing or copying the config files before deploying to my server, so I hope this will help someone else save a bit of time.