从 nuget 包中获取 files/content/assets

Getting files/content/assets from nuget packages

当 Visual Studio 项目使用 时,如何访问包中的文件? 例如,"Newtonsoft.Json" V12.0.3 包含除 Newtonsoft.Json.Dll 之外的几个文件 - 例如 newtonsoft.json.0.3\lib\net20\Newtonsoft.Json.xmlnewtonsoft.json.0.3\LICENSE.md.

我发现 GeneratePathProperty - 这很好,但在 VS2017 中构建 SDK 项目时它不起作用。 (在构建旧式框架项目时,它确实有效)。

<IncludeAssets> 似乎什么也没做。

我的 csproj 文件的一部分:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>

    <PackageReference Include="Newtonsoft.Json" Version="12.0.3" GeneratePathProperty="true">
        <IncludeAssets>all</IncludeAssets>
    </PackageReference>

</Project>

现在,如果我从命令行构建 (msbuild.exe 15.9.21+g9802d43bc3) msbuild /t:Restore;Rebuild /p:Configuration=Release /p:Platform="Any CPU" MyProject.sln

MyProject.csproj.nuget.g.props 包含

  <PropertyGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
    <PkgNewtonsoft_Json Condition=" '$(PkgNewtonsoft_Json)' == '' ">%userprofile%\.nuget\packages\newtonsoft.json.0.3</PkgNewtonsoft_Json>
  </PropertyGroup>

这很棒,因为我可以根据需要在我的项目文件中使用 $(PkgNewtonsoft_Json) 来获取这些文件。

但是,当我从 VS2017 (V15.9.17) 内部构建时,我的 *PROPS 文件没有定义这个符号:-(

-------- 更新 --------

好的,重新启动并再次尝试后它成功了:-) 我必须将 Targets="restore;build" 更改为 Targets="restore;" 否则我会出错。给定 Lib1 和 Lib2,其中 Lib2 依赖于 Lib1,我得到这个错误

Target CoreCompile:
  Using shared compilation with compiler from directory: C:\Program Files (x86)\Microsoft Visual Studio17\Community\MSBuild.0\Bin\Roslyn
  CSC : error CS0006: Metadata file 'C:\src\...\build\Lib2\bin\Debug\netstandard2.0\Lib2.dll' could not be found
Done building target "CoreCompile" in project "Lib1.csproj" -- FAILED.

然后,在构建整个解决方案之后 - 它失败了,当我再次构建 Lib1 时它失败了

error MSB4006: There is a circular dependency in the target dependency graph involving target "Build".```



Which is great, because I can use $(PkgNewtonsoft_Json) in my project file as needed to get those files. But, when I build from inside VS2017 (V15.9.17), my *PROPS file does not get this symbol defined

经过深入研究和测试,我发现这只是VS2017中的一个问题IDE,而VS2019已经修复了该问题。

xxx.csproj.nuget.g.propsrestore 过程生成。而在VS2017中,对于新SDK的项目,VSIDE不同于msbuild还原机制的还原包机制存在较大的不兼容问题,导致出现各种情况。幸运的是,VS2019 修复了这个问题。

作为建议,您可以尝试以下步骤:

1)下载the latest VS2019并使用。

2) 添加一个自定义目标,其中包含使用 MSBuild 将您的项目构建到 xxxxx.csproj file.

中的任务
<Target Name="OnceBuild" AfterTargets="Build">

    <MSBuild Projects="$(SolutionDir)$(SolutionFileName)" Targets="restore;build" Properties="Configuration=Release;Platform=Any CPU">        
    </MSBuild>   
 </Target>

它将生成由MSBuild restore创建的xxx.csproj.nuget.g.props。虽然这包含错误 MSB4006,但它不会影响 VS 中的构建过程 IDE,您不必担心。

更新 1

只需在 MSBuild

中将自定义目标添加到 运行 msbuild -t:store
<Target Name="OnceBuild" AfterTargets="Build">    
  <MSBuild Projects="$(SolutionDir)$(SolutionFileName)" Targets="restore" Properties="Configuration=Release;Platform=Any CPU">        
   </MSBuild>   
</Target>