Friday, February 5, 2010

Dynamically Change Environment Specific Web.Config file

When ever we develop ASP.NET application, we keep our entire environmental specific settings into web.config file. Based on where we deploy the application (Dev, Test, Prod), we will comment out other environments which is a manually process. Personally I prefer different web.config files for different environments and based on the Build option you select it should dynamically create the appropriate web.config file for that environment.


Below I mentioned step by step procedure to achieve that functionality.

  1. Create Files with following Extenstions
    • Web.config.Local
    • Web.config.Debug
    • Web.config.Release
  2. Right click the Project and select Properties
  3. Select Build Events Tab and paste the following code in Pre-Build Event Command Line text box.

    "$(ProjectDir)ChangeConfig.bat" "$(ProjectDir)web.config.$(ConfigurationName)" "$(ProjectDir)web.config"
  4. Create a Text file with name (ChangeConfig.bat) and copy the following code.

    @echo off
    echo Comparing two files: %1 with %2
    if not exist %1 goto File1NotFound
    if not exist %2 goto File2NotFound
    fc %1 %2
    if %ERRORLEVEL%==0 GOTO NoCopy
    echo Files are not the same. Copying %1 over %2
    echo Removing Readonly Attribute on File %2
    attrib -r %2
    copy %1 %2 /y
    echo Set Readonly Attribute on File %2
    attrib +r %2
    goto END
    :NoCopy
    echo Files are the same. Did nothing
    goto END
    :File1NotFound
    echo %1 not found.
    goto END
    :File2NotFound
    copy %1 %2 /y
    goto END
    :END
    echo Done.
  5. Select Build Menu in VS 2005 and select Configuration Manager.
  6. Select New

  7. Name it DebugLocal and select Debug.
  8. Click OK button.

There you go, from now onwards if you change the build, it automatically copies appropriate web.config file.

Before you leave:
  • Tell me whether you like this article or not? Rate this post accordingly by selecting the stars below.
  •  Any suggestion, question or comment? Please post it in the comments below.

0 comments:

Post a Comment