How can I tell compiler to copy wwwroot from one project to Tests proj?

Viewed 3378

Let's say I have this structure of projects:

- AppRunner
        | - Apprunner.csproj
        | - wwwroot


- Tests  
        | - Tests.csproj
        | - bin
                | - debug
                        | - netcoreapp2.1
                                        | - I want copy wwwroot here

I'd want to tell compiler to copy wwwroot with all items and folders inside to output folder of tests

but I'd want it to work fine not only on Windows but also on Linux

I addedd to Tests.csproj this:

<ItemGroup>
    <None Update="..\AppRunner\wwwroot\*">
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
</ItemGroup>

but it doesn't really work

2 Answers

In your Tests.csproj you could set up a link to your wwwroot folder:

<ItemGroup>
  <Content Include="..\AppRunner\wwwroot\**" Link="wwwroot\%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="Always" />
</ItemGroup>

In Visual Studio this will look like a regular wwwroot folder in your Tests project, but it is actually just a link to the folder in AppRunner. When you specify CopyToOutputDirectory this folder and its contents will be copied to the bin folder when you build the Tests project

As @cyptus suggested you could utilize MsBuild tasks. For example you can add task that will copy contents of wwwroot anywhere you want after each build. To do so add post build task at the end of your Apprunner.csproj.

 <Target Name="CopyWwwroot" AfterTargets="Build">
   <ItemGroup>
        <CopyItems Include="$(SolutionDir)\Apprunner\wwwroot\**\*.*" />
  </ItemGroup>
     <Copy 
      SourceFiles="@(CopyItems)" 
      DestinationFolder="..\Tests\bin\$(Configuration)\$(TargetFramework)\wwwroot\%(RecursiveDir)" 
      SkipUnchangedFiles="false"
      OverwriteReadOnlyFiles="true" 
      Retries="3"
      RetryDelayMilliseconds="300"/>
</Target>

$(Configuration) is current configuration e.g. debug or release

$(TargetFramework) is framework you are building with in your scenario netcoreapp2.1

If you really want you can have those values hardcoded. You can read more about copy task on docs https://docs.microsoft.com/en-us/visualstudio/msbuild/copy-task?view=vs-2019

Also keep in mind that you can set condition on target for example to copy only if you are building in release.

Related