tags:

views:

723

answers:

2

I have a C# project say MyProject.csproj located at "C:\Projects\MyProject\". I also have files that I want copied into the output directory of this project. But, the files are at the location "C:\MyContentFiles\", i.e. they are NOT within the project cone. This directory has sub-directories as well. The contents of the directory is not managed. Hence I have to include all what is under it.

When I include them as 'Content' in the project, they are copied, but the directory structure is lost. I did something like this:-

Content Include="..\..\MyContentFiles\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>

How do I copy these files/directories recursively into the output directory of the project with the directory structure preserved?

+1  A: 

You need to add file as a link:

  1. Right click on the project in VS.
  2. Add -> Existing Item...
  3. Find the file.
  4. Select it and.
  5. Add as a Link (drop down in the Add Button in the dialog).
  6. Open the properties of the file and set "Copy to Output Directory" to "Copy always".

BUT You cannot do it for the directory tree.
Instead you need to write post-build task for that. This is a sample that will get you stared.

Dmytrii Nagirniak
+1  A: 

The following, which you would add to the bottom of your project file, will copy your content files maintaining the directory structure in a after build event to the target directory $(TargetDirectory) of your build (typically $(MSBuildProjectDirectory)\bin\Debug ).

<ItemGroup>
    <ExtraContent Include="$(MSBuildProjectDirectory)\..\..\MyContentFiles\**">
</ItemGroup>

<Target Name="AfterBuild">
    <Copy 
        SourceFiles="@(ExtraContent)" 
        DestinationFiles="@(ExtraContent->'$(TargetDir)\%(RecursiveDir)%(Filename)%(Extension)')" 
        SkipUnchangedFiles="true" >
</Target>

If these files needed to go in a directory named MyContentFiles, you could add this before the copy:

<MakeDir Directories="$(TargetDir)\MyContentFiles" Condition=" !Exists('$(TargetDir\MyContentFiles') " />

and change

<Copy 
            SourceFiles="@(ExtraContent)" 
            DestinationFiles="@(ExtraContent->'$(TargetDir)\%(RecursiveDir)%(Filename)%(Extension)')" 
            SkipUnchangedFiles="true" >

To

<Copy 
            SourceFiles="@(ExtraContent)" 
            DestinationFiles="@(ExtraContent->'$(TargetDir)\MyContentFiles\%(RecursiveDir)%(Filename)%(Extension)')" 
            SkipUnchangedFiles="true" >
Todd
Your transforms have a type-o: @(ExtraContent)->'...') should be @(ExtraContext->'...'). Otherwise good answer!
alexdej