如何在Visual Studio中启用NuGet包还原?

Dan*_*ieu 263 c# asp.net nuget nuget-package-restore visual-studio-2015

堆栈上有一个类似的帖子,但它对我的问题没有帮助,可能是因为我使用的是Visual Studio 2015.

如何在VS2015中显示"启用NuGet包还原"选项?

我选择了File> New Project并创建了一个空的ASP.NET Web应用程序.我正在寻找这个菜单选项.

在此输入图像描述

我应该提一下,我已经在我的项目文件夹中查找了任何预先存在的nuGet文件,但没有.

Vin*_*lly 241

花了太长时间,但我终于找到了关于将MSBuild集成解决方案迁移到自动包恢复的文档,我能够使用此处描述的方法解决问题.

  1. '.nuget'解决方案中删除解决方案目录
  2. nuget.targets从您的.csproj.vbproj文件中删除所有引用.虽然没有得到官方支持,但如果您有许多需要清理的项目,该文档会链接到PowerShell脚本.我手动编辑了我的手册,所以我不能就我的经验给出任何反馈.

手动编辑文件时,您将找到以下内容:

解决方案文件(.sln)

Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{F4AEBB8B-A367-424E-8B14-F611C9667A85}"
ProjectSection(SolutionItems) = preProject
    .nuget\NuGet.Config = .nuget\NuGet.Config
    .nuget\NuGet.exe = .nuget\NuGet.exe
    .nuget\NuGet.targets = .nuget\NuGet.targets
EndProjectSection
EndProject
Run Code Online (Sandbox Code Playgroud)

项目文件(.csproj/.vbproj)

  <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
  </Target>
Run Code Online (Sandbox Code Playgroud)

  • 为了节省一点时间,从@VinneyKelly提到的GitHub存储库执行的脚本是migrateToAutomaticPackageRestore.ps1,它的神奇之处在于! (5认同)
  • 我在这里完全错过了一些东西.当我使用这种方法时,我会在每个解决方案中安装一大堆软件包.我有一个包含10个软件包的解决方案和另一个具有完全相同软件包的解决方案:创建了两个不同的目录,每个目录包含10个软件包.使用这种方法,如何将所有包合并到一个目录中(如旧的VS2013方法允许编辑NuGet.Config文件)? (3认同)

Qua*_*kly 60

Microsoft已经放弃了对VS2015中"启用NuGet包还原"的支持,您需要进行一些手动更改以迁移旧解决方案或将该功能添加到新解决方案中.新功能在NuGet Package Restore中得到了很好的描述.

此处还有现有项目的迁移指南(如前所述):NuGet迁移指南

升级时:

  1. 不要删除.nuget目录.
  2. 删除nuget.exe和nuget.targets文件.
  3. 离开nuget.config.
  4. 手动清除对NuGet目标的任何引用的每个项目文件.提到的Powershell脚本似乎造成的伤害大于好处.

创建新项目时:

  1. 在Visual Studio 2015解决方案中,创建名为.nuget的解决方案目录.
  2. 创建解决方案目录的实际目录(.sln文件所在的目录)并将其命名为.nuget(请注意,解决方案目录与实际文件系统目录不同,即使它们具有相同的名称).
  3. 在名为nuget.config的.nuget目录中创建一个文件.

  4. 将'nuget.config'添加到步骤2中创建的解决方案目录中.

  5. 将以下文本放在nuget.config文件中:

    <?xml version="1.0" encoding="utf-8"?> <configuration> <config> <add key="repositorypath" value="$\..\..\..\..\Packages" /> </config> <solution> <add key="disableSourceControlIntegration" value="true" /> </solution> </configuration>

此配置文件允许您在一个位置合并所有软件包,因此您的文件系统上没有相同软件包的20个不同副本.相对路径将根据您的解决方案目录体系结构而变化,但它应指向所有解决方案通用的目录.

执行第5步后,您需要重新启动visual studio.Nuget在您执行此操作之前无法识别更改.

最后,您可能必须使用"Nuget Package Manager for Solutions"来卸载然后重新安装软件包.我不知道这是否是我运行的Powershell脚本的副作用,或者只是一种让NuGet重新投入使用的方法.一旦我完成了所有这些步骤,当我从TFVC中检查项目时,我的复杂构建体系结构在完成新软件包时可以完美运行.


小智 33

您可以选择从"packages"文件夹中删除所有文件夹,然后选择"管理解决方案的NuGet包...".在这种情况下,NuGet Packages Windows上会出现"Restore"按钮.

  • +1这对我有用,请注意,恢复按钮会弹出窗口顶部,就在选项卡下方.说:"此解决方案中缺少一些NuGet软件包.点击从您的在线软件包源恢复." (6认同)

Jac*_*ler 20

正如Mike已经提到的,VS2015中没有"启用NuGet包恢复"选项.您必须手动调用还原过程.一个不错的方法 - 没有弄乱文件和目录 - 正在使用NuGet包管理控制台:点击"快速启动"字段(通常在右上角),输入console,打开管理控制台,然后输入命令:

Update-Package –reinstall
Run Code Online (Sandbox Code Playgroud)

这将重新安装解决方案中所有项目的所有包.要指定单个项目,请输入:

Update-Package –reinstall -ProjectName MyProject
Run Code Online (Sandbox Code Playgroud)

当然,仅当Restore按钮(有时由VS2015提供)不可用时才需要这样做.这里列出并解释了更多有用的更新命令:https://docs.microsoft.com/en-us/nuget/consume-packages/reinstalling-and-updating-packages


Yen*_*the 13

如果您遇到任何问题或缺少任何软件包,只需在项目中单击鼠标右键,然后选择" 管理NuGet软件包以获取解决方案...... ".单击此按钮后,将打开一个屏幕,您会看到菜单栏中显示"恢复": 恢复

单击它,将自动安装所需的包.
我相信这就是你所寻找的,这解决了我的问题.

  • 但这只有在警报栏出现时才有用,但在我的情况下则不然. (3认同)
  • 手动安装软件包的步骤完全忽略了自动还原的要点. (2认同)

Abd*_*zad 9

使用此命令恢复所有包

dotnet restore
Run Code Online (Sandbox Code Playgroud)


Eri*_*let 6

使用nuget软件包从Vx20XX升级到VS2015的项目时,您可能遇到nuget软件包问题.

错误消息示例:此项目引用此计算机上缺少的NuGet包.启用NuGet Package Restore以下载它们.

更新2016-02-06:我有一个信息的链接,但它不再工作.我怀疑最近的路径已经解决了这个问题???

我修复了我编写一个程序的问题,该程序执行MSBuild集成包恢复与自动包恢复

您可以在此处下载该工具的可执行文件.

请让我知道结果:-)!

在此输入图像描述

代码作为参考:

<Window x:Class="FixNuGetProblemsInVs2015.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:FixNuGetProblemsInVs2015"
        mc:Ignorable="d"
        Title="Fix NuGet Packages problems in Visual Studio 2015 (By Eric Ouellet)" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="10"></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>

        <TextBlock Grid.Row="0" Grid.Column="0">Root directory of projects</TextBlock>
        <Grid Grid.Row="0" Grid.Column="2">
            <Grid.ColumnDefinitions>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition Width="Auto"></ColumnDefinition>
            </Grid.ColumnDefinitions>

            <TextBox Grid.Column="0" Name="DirProjects"></TextBox>
            <Button Grid.Column="1" VerticalAlignment="Bottom" Name="BrowseDirProjects" Click="BrowseDirProjectsOnClick">Browse...</Button>
        </Grid>

        <!--<TextBlock Grid.Row="1" Grid.Column="0">Directory of NuGet Packages</TextBlock>
        <Grid Grid.Row="1" Grid.Column="2">
            <Grid.ColumnDefinitions>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition Width="Auto"></ColumnDefinition>
            </Grid.ColumnDefinitions>

            <TextBox Grid.Column="0" Name="DirPackages"></TextBox>
            <Button Grid.Column="1"  Name="BrowseDirPackages" Click="BrowseDirPackagesOnClick">Browse...</Button>
        </Grid>-->

        <TextBox Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3" Name="TxtLog" IsReadOnly="True"></TextBox>

        <Button Grid.Row="3" Grid.Column="0" Click="ButtonRevertOnClick">Revert back</Button>
        <Button Grid.Row="3" Grid.Column="2" Click="ButtonFixOnClick">Fix</Button>
    </Grid>
</Window>


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using System.Xml.Linq;
using Application = System.Windows.Application;
using MessageBox = System.Windows.MessageBox;

/// <summary>
/// Applying recommanded modifications in section : "MSBuild-Integrated package restore vs. Automatic Package Restore"
/// of : http://docs.nuget.org/Consume/Package-Restore/Migrating-to-Automatic-Package-Restore
/// </summary>

namespace FixNuGetProblemsInVs2015
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            DirProjects.Text = @"c:\prj";
            // DirPackages.Text = @"C:\PRJ\NuGetPackages";
        }

        private void BrowseDirProjectsOnClick(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();
            dlg.SelectedPath = DirProjects.Text;
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                DirProjects.Text = dlg.SelectedPath;
            }
        }

        //private void BrowseDirPackagesOnClick(object sender, RoutedEventArgs e)
        //{
        //  FolderBrowserDialog dlg = new FolderBrowserDialog();
        //  dlg.SelectedPath = DirPackages.Text;
        //  if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        //  {
        //      DirPackages.Text = dlg.SelectedPath;
        //  }
        //}

        // private string _dirPackages;

        private void ButtonFixOnClick(object sender, RoutedEventArgs e)
        {
            DoJob(false);
        }

        private void ButtonRevertOnClick(object sender, RoutedEventArgs e)
        {
            DoJob(true);
        }

        private void DoJob(bool revert = false)
        {
            TxtLog.Text = "";

            string dirProjects = DirProjects.Text;
            // _dirPackages = DirPackages.Text;

            if (!Directory.Exists(dirProjects))
            {
                MessageBox.Show("Projects directory does not exists: " + dirProjects);
                return;
            }

            //if (!Directory.Exists(_dirPackages))
            //{
            //  MessageBox.Show("Packages directory does not exists: " + _dirPackages);
            //  return;
            //}

            RecurseFolder(dirProjects, revert);
        }

        private void RecurseFolder(string dirProjects, bool revert = false)
        {
            if (revert)
            {
                Revert(dirProjects);
            }
            else
            {
                FixFolder(dirProjects);
            }

            foreach (string subfolder in Directory.EnumerateDirectories(dirProjects))
            {
                RecurseFolder(subfolder, revert);
            }
        }

        private const string BackupSuffix = ".fix_nuget_backup";

        private void Revert(string dirProject)
        {
            foreach (string filename in Directory.EnumerateFiles(dirProject))
            {
                if (filename.ToLower().EndsWith(BackupSuffix))
                {
                    string original = filename.Substring(0, filename.Length - BackupSuffix.Length);
                    if (File.Exists(original))
                    {
                        File.Delete(original);                                          
                    }
                    File.Move(filename, original);
                    Log("File reverted: " + filename + " ==> " + original);
                }
            }
        }

        private void FixFolder(string dirProject)
        {
            BackupFile(System.IO.Path.Combine(dirProject, "nuget.targets"));
            BackupFile(System.IO.Path.Combine(dirProject, "nuget.exe"));

            foreach (string filename in Directory.EnumerateFiles(dirProject))
            {
                if (filename.ToLower().EndsWith(".csproj"))
                {
                    FromProjectFileRemoveNugetTargets(filename);
                }
            }
        }

        private void BackupFile(string path)
        {
            if (File.Exists(path))
            {
                string backup = path + BackupSuffix;
                if (!File.Exists(backup))
                {
                    File.Move(path, backup);
                    Log("File backup: " + backup);
                }
                else
                {
                    Log("Project has already a backup: " + backup);
                }
            }
        }

        private void FromProjectFileRemoveNugetTargets(string prjFilename)
        {
            XDocument xml = XDocument.Load(prjFilename);

            List<XElement> elementsToRemove = new List<XElement>();

            foreach (XElement element in xml.Descendants())
            {
                if (element.Name.LocalName == "Import")
                {
                    var att = element.Attribute("Project");
                    if (att != null)
                    {
                        if (att.Value.Contains("NuGet.targets"))
                        {
                            elementsToRemove.Add(element);
                        }
                    }
                }

                if (element.Name.LocalName == "Target")
                {
                    var att = element.Attribute("Name");
                    if (att != null && att.Value == "EnsureNuGetPackageBuildImports")
                    {
                        elementsToRemove.Add(element);
                    }
                }
            }

            if (elementsToRemove.Count > 0)
            {
                elementsToRemove.ForEach(element => element.Remove());
                BackupFile(prjFilename);
                xml.Save(prjFilename);
                Log("Project updated: " + prjFilename);
            }
        }

        private void Log(string msg)
        {
            TxtLog.Text += msg + "\r\n";
        }

    }
}
Run Code Online (Sandbox Code Playgroud)


San*_*wal 5

转到visual studio中的References,看看哪些包丢失了.现在右键单击Visual中的Solution,然后单击文件资源管理器中的打开文件夹.现在打开包文件夹并删除丢失的包文件夹.打开visual studio,然后构建解决方案.所有丢失的包都将被恢复.如果我帮忙,请将此标记为答案.


Man*_*rma 5

我在尝试构建示例项目gplus-quickstart-csharp-master 时遇到了同样的问题。

我仔细查看了错误消息,并找到了克服此错误的解决方法,希望这会有所帮助。

  • 右键单击解决方案文件并在 Windows 资源管理器中打开。
  • 使用NuGet.Config、NuGet.exe、NuGet.targets复制.nu​​get文件夹(下载链接或简单地从其他项目复制并替换)
  • 尝试重建解决方案。

享受 !!