如何将其他文件添加到 nuget 包并在 nuget 包代码中引用这些文件?

问题描述

我想在 nuget 包中提供一些额外的文件,以便无论何时何地安装,这些文件都会在正确的位置提供。

我遇到的问题是我的代码需要引用这些文件才能运行。

文件是单个目录中的 3 个 .exe 文件一个 .jar 文件...

enter image description here

这是引用该文件夹位置的代码...

var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\WebDrivers\\Drivers\\";

我希望能够打包此代码文件,以便在安装此 nuget 包时,此代码将指向有效位置。

我该怎么做?

我尝试的第一件事是将以下内容添加.csproj 文件

<ItemGroup>
  <None Update="WebDrivers\Drivers\chromedriver.exe">
    <copyToOutputDirectory>PreserveNewest</copyToOutputDirectory>
  </None>
  <None Update="WebDrivers\Drivers\geckodriver.exe">
    <copyToOutputDirectory>PreserveNewest</copyToOutputDirectory>
  </None>
  <None Update="WebDrivers\Drivers\msedgedriver.exe">
    <copyToOutputDirectory>PreserveNewest</copyToOutputDirectory>
  </None>
  <None Update="WebDrivers\Drivers\selenium-server-standalone-3.141.0.jar">
    <copyToOutputDirectory>PreserveNewest</copyToOutputDirectory>
  </None>
</ItemGroup>

这仅在您在同一解决方案中引用项目时才有效。在您完成 dotnet pack 并将软件包安装到不同的项目/解决方案后,它不起作用。

我尝试的第二件事是这里接受的答案...

Copy files from Nuget package to output directory with MsBuild in .csproj and dotnet pack command

但我无法复制任何文件...

enter image description here

SASelenium.Framework.csproj

  <ItemGroup Label="FilesTocopy">
    <Content Include="SASelenium.Framework.targets" PackagePath="build/SASelenium.Framework.targets" />
    <Content Include="LogFiles\*.config" Pack="true" PackagePath="contentFiles\LogFiles">
      <PackagecopyToOutput>true</PackagecopyToOutput>
    </Content>
  </ItemGroup>

SASelenium.Framework.targets

<ItemGroup>
  <LogFiles Include="$(MSBuildThisFileDirectory)\..\contentFiles\LogFiles\*.config" />
</ItemGroup>
<Target Name="copyLogFiles" BeforeTargets="Build">
  <copy SourceFiles="@(LogFiles)" DestinationFolder="$(TargetDir)copiedLogFiles\" />
</Target>

我在构建安装此包的项目时没有看到任何文件

即使这确实有效,我如何确保包中的代码在从任何项目运行时始终指向这些文件

解决方法

我通过将我的 .csproj 更新为每个必需文件的以下内容来解决此问题...

<Content Include="WebDrivers\Drivers\chromedriver.exe">
  <CopyToOutputDirectory>Always</CopyToOutputDirectory>
  <PackageCopyToOutput>true</PackageCopyToOutput>
  <pack>true</pack>
</Content>

dotnet pack 后,我可以通过检查包来查看文件

enter image description here

将 nuget 包添加到新项目并构建解决方案后,我能够看到 bin 文件夹中的文件...

enter image description here

这意味着根据当前正在执行的程序集查找文件夹的代码按预期工作。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...