如何更改 Visual Studio 项目中的 NuGet 包引用以使用 Nuget.config

How to change the NuGet-package reference in a Visual Studio project to use Nuget.config

我有一个 Visual Studio 项目文件,扩展名为 .csproj。里面有这样的引用:

<Import Project="..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props"....

我现在已经在解决方案文件夹的父文件夹中创建了一个 NuGet.config 文件。我删除了本地 "packages" 文件夹。在新的 nuget.config 中,我设置了一个用于存储包的公共位置。

nuget.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <config>
        <add key="repositoryPath" value="D:\Data\NuGet" />
    </config>
    <packageRestore>
        <add key="enabled" value="True" />
    </packageRestore>
</configuration>

构建时出现此错误:

This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information... The missing file is ..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props.

我该如何解决这个问题?

如果我必须手动替换项目文件中的 (Import Project="..\packages...) 元素,我应该将其更改为什么,以便它遵循 Nuget.config?

If I manually have to replace the (Import Project="..\packages...) elements in the project file, what should I change it to, so that it follows the configuration from the Nuget.config?

因为您使用了新的 nuget.config 文件,它改变了本地 nuget 引用的路径(像这样 <add key="repositoryPath" value="xxxxxx" />)。

Restore只会恢复丢失的nuget包,但不会更改为使用xxx.csproj中新的nuget包位置。

所以你可以按照我的步骤来解决问题:

解决方案

1) 工具-->Nuget包管理器-->包管理器控制台-->

键入 Update-Package -reinstall 重新安装这些包以引用新的正确路径。

2) 进入 xxxx.csproj 文件,删除这些重复的、旧的 import 信息,例如:

 <Import Project="..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\..\..\..\..\..\installed_packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" />

 <Error Condition="!Exists('..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props'))" />

3) 然后重建你的项目,就会解决这个问题。

更新 1

新的Nuget.config文件会指定新安装的nuget包使用新的参考地址,但对于之前安装的nuget包,xxx.csporj文件中的参考地址将保持旧地址. Restore过程只是恢复了新路径下的nuget包,而没有对xxx.csproj文件中的nuget引用做任何改动,所以只能重新安装。

外,导入节点由Microsoft.Net.Compilers props文件从microsoft.net.compilersnuget包中的build文件夹创建。而 it is a nuget mechanism 可以在安装 nuget 包时在 xxx.csproj 文件中进行一些操作。

但是,这个文件也比较特殊,当你改变nuget引用路径的时候。 因为nuget启用了新地址机制,在卸载过程中,仍然无法识别Microsoft.Net.Compilers.props的旧地址,所以无法卸载。 其实,当你执行reinstall nuget package时,xxx.csproj文件中已经创建了一个新的地址。看到这个:

所以您应该只删除旧地址中的重复文件。

Visual Studio option to change the Nuget Package References

  • 在 Visual Studio 工具中 => Nuget 包管理器 => 包源。
  • 您可以在此处更改包源。