Visual Studio Post-Build event - How to copy files

2020-04-21 02:43发布

问题:

How to copy needed binary files (e.g. dlls, icons, tools, doc) into the target directory in the bin folder?

There is an obvious integrated possibility: Including the file as been done with source files and mark in the file properties in "Copy to output directory" as "Copy always" or "Copy newer".

But this works only, if that binary files stay included in the main project folder. If you tidy up, and put those files in a subfolder just to differentiate from source files, that subfolder is created in the target directory 1:1, and the resource files are not in the root target dir.

Related question: VS PostBuild Event - Copy file if it exists

回答1:

Answering my own question to share my knowledge.

Given you want to copy all files in a VS project´s subfolder "RuntimeEnv":

Under the build properties of any project file there is a tab "Build events" with Pre-build and Post-build commandline possibilities to include such copy or similar build requirements without setting up a TFS build definition.

There you could include batch like commands and have access to some prebuild variables. See for example the link in the question.

copy doesn´t provide enough features. In the following, I mention a solution for xcopy and robocopy

As I prefer robocopy.exe as very fast, reliable and a build-in option to copy only newer files (/XO), I use the following instead of a simple "copy" command :

robocopy.exe /XO "$(ProjectDir)RuntimeEnv" "$(TargetDir)." >nul 2>&1
exit 0

There are two specialties of robocopy worked around here:

  1. The "." after the "$(TargetDir)" is necessary because robocopy doesn´t like paths ending with backslash which is the case here.

  2. The last line is necessary because robocopy exits with a returncode containing the number of files copied, so "0" is not the same as successful as expected.

It would be possible to add some MSBuild target lines to change the expected returncode, but doing it in the Post-Build event is most simple.

HTH.

P.S. As Hans Passant pointed out in a comment, xcopy /D is an easier solution. It is- and if no other properties or parameters of robocopy are useful, this could be preferred.

This would then make the line:

xcopy.exe /D /Y "$(ProjectDir)RuntimeEnv\*.*" "$(TargetDir)"

The output lines of xcopy would not disturb normally, and give a hint what is happening at post-build - otherwise you could add >nul 2>&1 too.