Including content files in .csproj that are outside the project cone

Viewed 113744

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?

7 Answers

To include files in a folder for a .NET Core project,

<!--Just files-->
<ItemGroup>
  <None Update="..\..\MyContentFiles\**\*.*">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
</ItemGroup>
<!--Content files-->
<ItemGroup>
  <Content Include="..\..\MyContentFiles\**\*.*" Link="MyContentFiles\%(RecursiveDir)%(Filename)%(Extension)">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </Content>
</ItemGroup>

And the items' property "Copy to Output Directory" will be "Copy if newer":
Copy if newer

To ignore a file in a .Net Core project:

<ItemGroup>
 <Content Include="appsettings.local.json">
   <CopyToOutputDirectory Condition="Exists('appsettings.local.json')">PreserveNewest</CopyToOutputDirectory>
 </Content>
</ItemGroup>
Related