MSBuild。在构建之前创建 EmbeddedResource

R. *_*yev 3 c# msbuild csproj visual-studio

我想在编译主单元之前在程序集中嵌入本地引用。但是写的目标不起作用。

  <Target Name="EmbedLocal" BeforeTargets="CoreCompile">
    <Message Text="Run EmbedLocal for $(MSBuildProjectFullPath)..." Importance="high"/>    
    <ItemGroup>
      <EmbeddedResource Include="@( ReferencePath->WithMetadataValue( 'CopyLocal', 'true' )->Metadata( 'FullPath' ) )"/>
    </ItemGroup>
    <Message Text="Embed local references complete for $(OutputPath)$(TargetFileName)." Importance="high" />
  </Target>
Run Code Online (Sandbox Code Playgroud)

@(EmbeddedResource) 此时包含有效的路径列表。

更新:
现在我的导入文件包含:

<Project ToolsVersion="$(MSBuildToolsVersion)" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <EmbedLocalReferences Condition=" '$(EmbedLocalReferences)' == '' ">True</EmbedLocalReferences>
  </PropertyGroup>

  <Target Name="EmbedLocal" BeforeTargets="ResolveReferences" Condition=" '$(EmbedLocalReferences)' == 'True' ">
    <Message Text="Run EmbedLocal for $(MSBuildProjectFullPath)..." Importance="high"/>
    <ItemGroup>
      <EmbeddedResource Include="@(ReferenceCopyLocalPaths->WithMetadataValue( 'Extension', '.dll' )->Metadata( 'FullPath' ))">
        <LogicalName>%(ReferenceCopyLocalPaths.Filename)%(ReferenceCopyLocalPaths.Extension)</LogicalName>
      </EmbeddedResource>
    </ItemGroup>   
    <Message Text="Embed local references complete for $(OutputPath)$(TargetFileName)." Importance="high" />
  </Target>
</Project>
Run Code Online (Sandbox Code Playgroud)

它工作正常。输出程序集包含所有 .dll 引用作为 EmbeddedResource。

Leo*_*SFT 6

MSBuild。在构建之前创建 EmbeddedResource

您可以尝试对csproj 文件使用BeforeBuild操作以包含嵌入的资源:

  <Target Name="BeforeBuild">
    ... 
    <ItemGroup>
      <EmbeddedResource Include="..."/>
    </ItemGroup>
    ...
  </Target>
Run Code Online (Sandbox Code Playgroud)

现在 MSBuild 会将此文件作为嵌入资源添加到您的程序集中。

更新:

谢谢@Martin Ullrich。他指出了正确的方向,我们可以用<Target Name="EmbedLocal" BeforeTargets="PrepareForBuild">Directory.Build.props来解决这个问题。您可以检查它是否适合您。

  <Target Name="EmbedLocal" BeforeTargets="PrepareForBuild">
    ... 
    <ItemGroup>
      <EmbeddedResource Include="..."/>
    </ItemGroup>
    ...
  </Target>
Run Code Online (Sandbox Code Playgroud)

  • @MartinUllrich,你是对的。我已经用 BeforeTargets="PrepareForBuild" 对其进行了测试,它工作正常。在您告诉我之前,我不知道不鼓励“BeforeBuild”,这里是否有任何文档或博客可以解释原因,我想了解很多关于它的信息,请您提供一些有关它的链接吗?非常感谢 :)。 (2认同)