Conditional Visual Studio build event scripts

In some projects there’s a need for manual operations after compilation. It might be to copy files, sign code or whatever. Of course it would be great to make these operations automatic, and that’s what build event scripts in Visual Studio are for.

Basically a build event script is a BAT file with some variables that are replace by Visual Studio when executing it. You create a build event script in the Properties dialog box of the project and here’s an example of what it may look like (in this case we package a set of files from the project into a Zip archive used for deploying the application):

REM If Debug config, do nothing...
if $(ConfigurationName) == Debug then goto endif

mkdir $(TargetDir)Imports\
mkdir $(TargetDir)Reports\
mkdir $(TargetDir)Faktureringsunderlag\

del /F /Q $(TargetDir)Imports\*.*
del /F /Q $(TargetDir)Reports\*.*
del /F /Q $(TargetDir)Faktureringsunderlag\*.*

copy /Y $(ProjectDir)Imports\*.xlt $(TargetDir)Imports\
copy /Y $(ProjectDir)Reports\*.rpt $(TargetDir)Reports\
copy /Y $(ProjectDir)Faktureringsunderlag\*.xlt $(TargetDir)Faktureringsunderlag\

REM Create Zip archive
del /Q

$(SolutionDir)Utils\7z.exe a Faktureringsunderlag Imports Reports
ErrorHandler.dll janus*.dll Microsoft.ApplicationBlocks.Data.dll new_*.dll
new_SFIStarter.exe SFI*.dll Svea.exe Svea.exe.config


The example illustrates several points:

  • The operations are conditional, i.e. are not done in Debug compilation. There’s no point it taking that time if we’re about to deploy the application.
  • It makes sense to use options for the respective tool to disable prompting (e.g. “Are you sure you want to delete XXX”) since we’ll never be able to answer.
  • Any command line utility can be used. In this case I have downloaded the great 7-Zip util and copied it’s binaries into the solution so that it’s always available on every developer’s computer.

Kind of useful, ain’t it? Of course, there are other ways of doing this, e.g. using MSBuild, but I find this method easy to understand and manage.