How to recursively copy files using the <Copy> Task in MSBuild

From the MSBuild Team Blog

Have you ever run into a situation where you had to recursively copy files from one folder into another as a part of your build process?  We certainly have run into it a few times, and I thought I’d share with you a neat trick that involves the use of metadata and the Copy task.

Before you can copy a set of files, you need to be able to recursively add those files to an item list. Here’s how you do that when declaring items.

      <Compile Include=".\**\*.cs" /> 

The ** wildcard is used in item includes to indicate recursive includes.

So, once you have an item declared as such, you can rely on a piece of standard meta-data that goes with all items (i.e. RecursiveDir) to accomplish your recursive copy. The RecursiveDir metadata when used will return the evaluated value of the ** metadata for each item – and you can use that value to preserve the folder structure for each file when performing the copy. Here’s how you invoke the <Copy> task using this piece of metadata to copy recursively.

<Copy SourceFiles="@(Compile)" DestinationFolder="c:\foocopy\%(RecursiveDir)"></Copy>

Additional information can be found at the MSBuild Team Blog and the MSBuild Wiki.

Happy Visual Studio’ing!  Suggest a Tip of the Week!

Comments (1)
  1. Repeating a task for each item in a MSBuild item list is really easy if the task supports ; seperated lists, if not, well it’s still easy but trying to remember the syntax is another matter! This keeps catching me out and I’ve seen few examples of it

Comments are closed.

Skip to main content