首页 > 解决方案 > 使用 GeneratePackageOnBuild 和 contentFiles 构建 dotnet

问题描述

我有一个正在构建的项目dotnet build -c Release /p:Platform=x86 .\Foo.csproj。该csproj文件为 SDK 格式,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
  <PropertyGroup>
    <TargetFramework>net48</TargetFramework>
    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
    <AssemblyName>Foo</AssemblyName>
    <Company>Me</Company>
    <Authors>Me</Authors>
    <Version>4.12.5</Version>
    <AssemblyVersion>4.12.5.0</AssemblyVersion>
    <FileVersion>4.12.5.0</FileVersion>
    <Platforms>x86</Platforms>
    <UseWPF>true</UseWPF>
  </PropertyGroup>
  <ItemGroup>
    <ProjectReference Include="..\Bar.csproj">
      <!-- ... -->
    </ProjectReference>
  </ItemGroup>
  <ItemGroup Label="FilesToCopy">
    <Content Include="..\dependent.dll" Pack="true" PackagePath=".\lib\net48\" PackageCopyToOutput="true" />
    <None Include="image.jpg" Pack="true" PackagePath=".\contentFiles\any\any\" PackageCopyToOutput="true" />
  </ItemGroup>
  <ItemGroup>
    <None Update="tex_cardboard.jpg">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>
  <PropertyGroup>
    <TargetsForTfmSpecificBuildOutput>$(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage</TargetsForTfmSpecificBuildOutput>
  </PropertyGroup>
  <Target Name="CopyProjectReferencesToPackage" DependsOnTargets="ResolveReferences">
    <ItemGroup>
      <BuildOutputInPackage Include="@(ReferenceCopyLocalPaths-&gt;WithMetadataValue('ReferenceSourceTarget', 'ProjectReference'))" />
    </ItemGroup>
  </Target>
</Project>

这将在构建时生成一个包含image.jpgcontentFiles\any\any文件夹中的 nuget 包。

如果我理解正确,.nuspecnuget 包内的文件应包含:

    <contentFiles>
      <files include="**/*" buildAction="Content" />
    </contentFiles>

但事实并非如此。

如何在csproj文件中告知要作为内容包含而不是编译的图像文件?

标签: .netnugetnuget-package

解决方案


是的,除非您在项目文件中为资源定义自定义,否则包内的 NuSpec 文件将包含该contentFiles标签。它猜测此行为适用于文件,因为该文件的内容文件的默认路径已被覆盖,并且不再被检测为适用于 NuGet 约定的内容文件。从参考MS Build 目标PackagePath.csproj.csproj

如果未为它们指定 PackagePath,则此属性指定所有内容文件的默认位置。默认值为“内容;内容文件”。

默认情况下,所有内容都会添加到包内的 content 和 contentFiles\any<target_framework> 文件夹的根目录中,并保留相对文件夹结构,除非您指定包路径 [...]

尽管明确指出您可以PackagePath在具有不同构建操作的许多内容类型上使用,但没有提到这会导致不同的 NuSpec 文件,但实际上确实如此。

除了 Content 项之外,还可以使用 Compile、EmbeddedResource、ApplicationDefinition、Page、Resource、SplashScreen、DesignData、DesignDataWithDesignTimeCreateableTypes、CodeAnalysisDictionary、AndroidAsset、AndroidResource、BundleResource 或 None 的构建操作在文件上设置元数据。[...]

在您的csproj文件中,标签喜欢NoneContent确定构建操作,从而确定您的图像文件是否被嵌入、复制到输出文件夹或其他任何内容。但是,除了原始问题之外,设置Pack="true"足以将其自动包含在contenFiles\any\<Target framework moniker>包中的文件夹中。设置PackageCopyToOutput="true"会将其复制到使用项目的输出目录。


推荐阅读