How to make MSBuild correctly track files generate

2019-08-19 06:56发布

问题:

I have MSBuild code that takes files with a particular Build Action (CompileFoo in this example) and generates output files (with a different extension). This is the code I have so far:

<Target Name="BuildFoo" BeforeTargets="Compile"
    Inputs="@(CompileFoo)"
    Outputs="@(CompileFoo -> '$(OutputPath)%(RelativeDir)%(Filename).bin' )" >

    <!-- makefoo doesn't know how to create directories: -->
    <MakeDir Directories="$(OutputPath)%(CompileFoo.RelativeDir)"/>
    <Exec Command="makefoo -o &quot;$(OutputPath)%(CompileFoo.RelativeDir)%(CompileFoo.Filename).bin&quot; &quot;%(CompileFoo.Identity)&quot;" />

    <ItemGroup>
        <!-- Required so we can handle Clean: -->
        <FileWrites Include="@(CompileFoo -> '$(OutputPath)%(RelativeDir)%(Filename).bin' )"/>
    </ItemGroup>
</Target>

This works great if I include it in a project that generates the final EXE.

But now I want to make it work in a project that generates a DLL that is referenced by the EXE (C# with an assembly reference) and I need to get those generated items (the .bin files in the example) from the output directory of the DLL, into the output directory of the EXE.

I am trying to get something similar to the effect of this, when it occurs in the DLL project:

<Content Include="Test\Test.txt"><CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory></Content>

In this case the Test\Test.txt file ends up in the output folder of the EXE. Although I am not sure that is quite the same thing. (Does it copy from the original file, or the one from the DLL output folder?)

I'm trying to get something fairly compatible - specifically that will work on VS2010 and VS Mac.

回答1:

The trick here is to make the GetCopyToOutputDirectoryItems target return an additional AllItemsFullPathWithTargetPath item:

<Target Name="IncludeFoo" BeforeTargets="GetCopyToOutputDirectoryItems">
  <ItemGroup>
    <CompiledFoos Include="@(CompileFoo -> '$(OutputPath)%(RelativeDir)%(Filename).bin' )">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <TargetPath>%(RelativeDir)%(FileName).bin</TargetPath>
    </CompiledFoos>
    <AllItemsFullPathWithTargetPath Include="@(CompiledFoos->'%(FullPath)')"  />
  </ItemGroup>
</Target>

(testet using a current MSBuild 15 version) (Edited version tested with VS2010 -AR)