【问题标题】:how to add files to a projects output files from an MSBuild Task如何从 MSBuild 任务将文件添加到项目输出文件
【发布时间】:2017-04-28 12:56:36
【问题描述】:

给定一个在AfterTargets="AfterCompile" 中运行并生成一些文件的 MSBuild 任务,如何将这些文件包含在当前项目输出中,以便将文件复制到引用该项目的任何项目的 bin 目录中?

【问题讨论】:

  • 如果您知道编译前的文件路径,您可以使用 BeforeTargets="AssignTargetPaths" 添加一个目标并在其中填充 Content ItemGroup,如果 CopyToOutputDirectory 元数据设置为 true,它将被复制到取决于项目。编译后我不立即知道如何执行此操作。

标签: msbuild msbuild-task


【解决方案1】:

我不能保证这是正确的解决方案,但它似乎有效:

<Target Name="MyTarget" AfterTargets="AfterCompile">
  <PropertyGroup>
    <MyInput>D:\1.txt</MyInput>
    <MyOutput>$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)$(OutDir)\1.txt'))</MyOutput>
  </PropertyGroup>
  <Copy SourceFiles="$(MyInput)" DestinationFolder="$(OutDir)" SkipUnchangedFiles="true" />
  <ItemGroup>
    <AllItemsFullPathWithTargetPath Include="$(MyOutput)">
      <TargetPath>1.txt</TargetPath>
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </AllItemsFullPathWithTargetPath>
  </ItemGroup>
</Target>

相关逻辑在这里: http://sourceroslyn.io/#MSBuildTarget=GetCopyToOutputDirectoryItems http://sourceroslyn.io/#MSBuildItem=AllItemsFullPathWithTargetPath

基本上,我们依靠这样一个事实来确定要从依赖项目复制的文件列表,MSBuild 调用依赖项目的 GetCopyToOutputDirectoryItems 目标并使用其输出(即 AllItemsFullPathWithTargetPath)。

通过在最后一分钟将自己添加到 AllItemsFullPathWithTargetPath 中,当依赖项目调用我们时,我们会被接走。

【讨论】:

  • 请注意,MyTarget 中的 Copy 任务不是必需的,它只是假装在第一个项目的输出中“生成”1.txt。
【解决方案2】:

谢谢你,基里尔。这是一个很好的答案,它在尝试从不同项目的输出中复制 ETW 清单文件时帮助了我。下面是最终输出。

由于我只是简单地扩展了基里尔的答案,我不希望这个答案被接受。我在这里发布此内容,希望对其他人有所帮助。

<Target Name="IncludeEtwFilesInOutput"
        BeforeTargets="GetCopyToOutputDirectoryItems">

    <PropertyGroup>
        <EtwManifestFile>$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)$(OutDir)\My.etwManifest.man'))</EtwManifestFile>
        <EtwResourceFile>$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)$(OutDir)\My.etwManifest.dll'))</EtwResourceFile>
    </PropertyGroup>

    <ItemGroup>
        <AllItemsFullPathWithTargetPath Include="$(EtwManifestFile)">
            <TargetPath>My.etwManifest.man</TargetPath>
            <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </AllItemsFullPathWithTargetPath>
        
        <AllItemsFullPathWithTargetPath Include="$(EtwResourceFile)">
            <TargetPath>My.etwManifest.dll</TargetPath>
            <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </AllItemsFullPathWithTargetPath>
    </ItemGroup>
</Target>

【讨论】:

    猜你喜欢
    • 2013-04-11
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-03
    • 2012-12-21
    • 1970-01-01
    相关资源
    最近更新 更多