Add if conditional statement to the Visual Studio pre-build and post-build events

There are times when you want to execute statements in the pre-build and post-build events of a Microsoft Visual Studio project when certain conditions met. In the next example we will copy the environment specific config file to the web application folder if the configuration is set to “Local”.

To edit the pre-buld and post-buld events

  • In the Visual Studio Solution Explorer right click the startup project
  • Select Properties
  • On the left side select the Build Events tab
  • To edit the script in a larger, resizable  window click the Edit Pre-Build or Edit Post-Build buttons

 

visual studio edit pre-build event

 

  • Enter the following lines into the event edit region:


if $(ConfigurationName) ==  Local (
attrib "$(ProjectDir)Web.config" -r
copy "$(ProjectDir)Config_2012\$(ConfigurationName).xml" "$(ProjectDir)Web.config"
)

The commands will be interpreted line-by-line the same way as a DOS batch file, so it is important to place the opening parenthesis “(” in the same line as the if statement.

Leave a comment

Your email address will not be published. Required fields are marked *