首页 > 解决方案 > Nuget:包括一个 exe 作为运行时依赖项

问题描述

我有一个 .exe 应用程序,需要在构建时与我的 C# 应用程序一起分发。我正在尝试使用 Nuget 对其进行打包,以便在构建时将其包含在构建根目录中,但无法获得我想要的行为。

这是我的.nuspec文件中的内容:

<?xml version="1.0"?>
<package>
  <metadata>
    <id>my.id</id>
    <version>1.0.0</version>
    <authors>me</authors>
    <owners>me</owners>
    <licenseUrl>myurl</licenseUrl>
    <projectUrl>myurl</projectUrl>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>A copy of an .exe so we can easily distribute it 
       with our applications without needing to include it in our VCS repo</description>
    <releaseNotes>Initial test version</releaseNotes>
    <copyright>Copyright 2018</copyright>
    <dependencies>
    </dependencies>
    <packageTypes>
    </packageTypes>
    <contentFiles>
        <files include="any\any\myexe.exe" buildAction="None" copyToOutput="true" />
    </contentFiles>
  </metadata>
  <files>
    <file src="content\myexe.exe" target="content" />
  </files>
</package>

这会在我安装 Nuget 包时将 myexe.exe 文件放入我的 VS 项目,但在构建时它不会复制该文件。我想要的是在构建时将文件与我的其他应用程序文件一起安装并将其保留在我的 VS 项目之外。

我一直在这里阅读文档,但不确定如何制作 nuspec 文件。

更多细节:

Nuget 4.5.1

视觉工作室 2015

注意:<files>and<contentFiles>似乎是重复的功能。我想同时使用两者,因为我知道这将为 VS2017 提供面向未来的证明

标签: c#visual-studionuget

解决方案


Nuget:包括一个 exe 作为运行时依赖项

首先,我知道你想为未来使用一些技术,但我们要知道,这些面向未来的技术往往有一定的限制和条件。

例如,<contentFiles>用于带有PackageReference的NuGet 4.0 +,Visual Studio 2015都不支持它们。有关详细信息,请参阅对内容文件使用 contentFiles 元素

如果您对此感兴趣<contentFiles>,可以阅读博客NuGet 现在已完全集成到 MSBuild中。

现在回到我们的问题,根据上面的信息,我们<contentFiles>在使用Visual Studio 2015时不应该使用。为了解决这个问题,我们需要.targets在构建项目时在nuget包中添加一个文件:

文件内容.targets

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <None Include="$(ProjectDir)myexe.exe">
      <Link>myexe.exe</Link>
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CustomToolNamespace></CustomToolNamespace>
    </None>
  </ItemGroup>
</Project>

.nuspec文件如下:

  <files>
    <file src="build\YouNuGetPackageName.targets" target="build\YouNuGetPackageName.targets" />
    <file src="content\myexe.exe" target="content\myexe.exe" />
  </files>

注意: .targets 文件的名称应与您的 nuget 包名称相同。

通过这种方式,当您构建项目时,MSBuild/VS 会将文件复制myexe.exe到输出文件夹。

此外,如果要将文件复制myexe.exe到其他目的地,可以将.targets文件的内容替换为复制任务,例如:

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

  <Target Name="CopyMyexe" BeforeTargets="Build">
  <Message Text="Copy CopyMyexe to the folder."></Message>
  <Copy
  SourceFiles="$(ProjectDir)myexe.exe"
  DestinationFolder="xxx\xxx\xx\myexe.exe"
/>
  </Target>
</Project>

有关一些帮助,请参阅创建本机包类似问题

希望这可以帮助。


推荐阅读