Execute batch commands before or after compilation using Pre-build or Post-build events

Have you ever wanted to execute a set of commands before or after the compilation, like copying the contents of the directory to the target compilation directory, or copy output of the compilation to a specified folder. This feature is integrated inside visual studio with the name; “Pre-build or Post-build event command line”. You access it from the project properties, in the build events tab.


If you want to do something before the compilation you enter the shell commands to pre-build, and post-build is the operations for after the compilation. We can use the predefined macros without hard copying the directory names. The edit window will guide us to find the macros.


Let’s say we want to copy the contents of the output directory to the root d:. What we do is to edit the post-build event command with the command :

copy /D $(TargetPath) c:\

When we build it. We just get the error, “The command “copy D:\DEV_Projects\sampleProj\bin\sample.dll d:" exited with code 1.” Trying to execute the code from command line you get a similar error ‘The system cannot find the file specified.’

copy D:\\DEV\\_Projects\\sampleProj\\bin\\sample.dll d:"
The system cannot find the file specified.

What we forget is the need for the quotations for the long directory and filenames.

copy /D \"$(TargetPath)\" "c:\"

As a result, we can do whatever bat file operations before or after the compilation.