Copy files without overwrite

Tony picture Tony · Nov 19, 2010 · Viewed 207.3k times · Source

I just can't seem to find a way on the command line to say "copy all the files from directory A to directory B, but if the file already exists in directory B, don't overwrite it, no matter which file is newer, and don't prompt me."

I have been through copy, move, xcopy & robocopy, and the closest I can get is that you can tell robocopy "copy A to B, but don't overwrite newer files with older files," but that doesn't work for me. I looked at xxcopy, but discarded it, as I don't want to have a third-party dependency on a Visual Studio post-build event that will require other SVN users to have that tool installed in order to do the build.

I want to add a command line to the post-build event in Visual Studio 2010 so that the files that are generated from the T4 templates for new EF model objects get distributed to the project folders to which they belong, but regenerated files for existing objects don't overwrite potentially edited destination files.

Since the T4 template regenerates, the source file is always newer, and I can't use the "newer" switch reliably, I don't think.

I use partial classes for those items for which I can, but there are other things I generate that can't use partial classes (e.g. generating a default EditorTemplate or DisplayTemplate *.ascx file).

Any one have any similar problems they have solved?

Answer

Dr. belisarius picture Dr. belisarius · Nov 19, 2010

Robocopy, or "Robust File Copy", is a command-line directory replication command. It has been available as part of the Windows Resource Kit starting with Windows NT 4.0, and was introduced as a standard feature of Windows Vista, Windows 7 and Windows Server 2008.

   robocopy c:\Sourcepath c:\Destpath /E /XC /XN /XO

To elaborate (using Hydrargyrum, HailGallaxar and Andy Schmidt answers):

  • /E makes Robocopy recursively copy subdirectories, including empty ones.
  • /XC excludes existing files with the same timestamp, but different file sizes. Robocopy normally overwrites those.
  • /XN excludes existing files newer than the copy in the destination directory. Robocopy normally overwrites those.
  • /XO excludes existing files older than the copy in the destination directory. Robocopy normally overwrites those.

With the Changed, Older, and Newer classes excluded, Robocopy does exactly what the original poster wants - without needing to load a scripting environment.

References: Technet, Wikipedia
Download from: Microsoft Download Link (Link last verified on Mar 30, 2016)