VS PostBuild Event - Copy file if it exists
Asked Answered
C

3

25

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.

Cash answered 10/7, 2012 at 21:48 Comment(2)
Is the file included as part of your Visual Studio project, or some external file?Agustinaah
It's not added the project - but it lives in the same folder as the project.Cash
D
38

Use "IF" command:

IF EXIST file.txt xcopy file.txt [destination_folder]\ /Y
Deerhound answered 10/7, 2012 at 21:55 Comment(0)
R
8

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

xcopy source_file_name dest_folder /u /y
Rattle answered 10/7, 2012 at 21:57 Comment(2)
For some reason, I couldn't get the /u to work properly if the file didn't exist - it exited with error "4".Cash
My fault. I misunderstood. I was thinking that you want to copy the origin only if it exists in the destination. /U serves to this purpose, not to check if the source file exist.Rattle
B
4

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.

Brutalize answered 15/1, 2021 at 22:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.