Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VS PostBuild Event - Copy file if it exists

Is there a simple way to copy a file in a post-build event for a Visual Studio project, but only if the file exists? (i.e. don't fail the build if the file doesn't exist)

I've tried some options using xcopy. But I feel so stupid - I can't seem to get my head around what switches I might need with xcopy.

like image 938
Brad Leach Avatar asked Jul 10 '12 21:07

Brad Leach


3 Answers

Use "IF" command:

IF EXIST file.txt xcopy file.txt [destination_folder]\ /Y
like image 60
Hailton Avatar answered Nov 02 '22 15:11

Hailton


Also without the IF EXIST but using the /U option of XCOPY

xcopy source_file_name dest_folder /u /y
like image 8
Steve Avatar answered Nov 02 '22 16:11

Steve


If you prefer to use "Copy to Output Directory" in the Properties panel (provided by Visual Studio when you right-click on a project-file and select "Properties"), you can do so with a little bit of text-editing. This will work for all versions of Visual Studio that use MSBuild (i.e. Visual Studio 2010 and onward).

First, choose an appropriate value for "Copy to Output Directory", such as "Copy always" or "Copy if newer". Save your changes to the project (e.g. "Save all" from the "File" menu).

Then, edit the project file in a text editor, and inside the opening tag of the newly-added <CopyToOutputDirectory> element, add an attribute like Condition="Exists('$(MSBuildProjectDirectory)\FILENAME')", ,where FILENAME is the path of the file being copied (i.e. as referred to in the parent element).

The GUI won't edit this setting properly in the future (i.e. it'll display "Do not copy" as the value if the file doesn't exist), but at least it'll work.

like image 3
ulatekh Avatar answered Nov 02 '22 14:11

ulatekh