Create windows install packages

Install and manage packages with the Package Manager Console in Visual Studio (PowerShell)

The NuGet Package Manager Console lets you use NuGet PowerShell commands to find, install, uninstall, and update NuGet packages. Using the console is necessary in cases where the Package Manager UI does not provide a way to perform an operation. To use nuget.exe CLI commands in the console, see Using the nuget.exe CLI in the console.

The console is built into Visual Studio on Windows. It is not included with Visual Studio for Mac or Visual Studio Code.

The commands listed here are specific to the Package Manager Console in Visual Studio, and differ from the Package Management module commands that are available in a general PowerShell environment. Specifically, each environment has commands that are not available in the other, and commands with the same name may also differ in their specific arguments. When using the Package Management Console in Visual Studio, the commands and arguments documented in this present topic apply.

Find and install a package

For example, finding and installing a package is done with three easy steps:

Open the project/solution in Visual Studio, and open the console using the Tools > NuGet Package Manager > Package Manager Console command.

Find the package you want to install. If you already know this, skip to step 3.

Run the install command:

All operations that are available in the console can also be done with the NuGet CLI. However, console commands operate within the context of Visual Studio and a saved project/solution and often accomplish more than their equivalent CLI commands. For example, installing a package through the console adds a reference to the project whereas the CLI command does not. For this reason, developers working in Visual Studio typically prefer using the console to the CLI.

Many console operations depend on having a solution opened in Visual Studio with a known path name. If you have an unsaved solution, or no solution, you can see the error, «Solution is not opened or not saved. Please ensure you have an open and saved solution.» This indicates that the console cannot determine the solution folder. Saving an unsaved solution, or creating and saving a solution if you don’t have one open, should correct the error.

Opening the console and console controls

Open the console in Visual Studio using the Tools > NuGet Package Manager > Package Manager Console command. The console is a Visual Studio window that can be arranged and positioned however you like (see Customize window layouts in Visual Studio).

By default, console commands operate against a specific package source and project as set in the control at the top of the window:

Selecting a different package source and/or project changes those defaults for subsequent commands. To overrride these settings without changing the defaults, most commands support -Source and -ProjectName options.

To manage package sources, select the gear icon. This is a shortcut to the Tools > Options > NuGet Package Manager > Package Sources dialog box as described on the Package Manager UI page. Also, the control to the right of the project selector clears the console’s contents:

The rightmost button interrupts a long-running command. For example, running Get-Package -ListAvailable -PageSize 500 lists the top 500 packages on the default source (such as nuget.org), which could take several minutes to run.

Install a package

Installing a package in the console performs the same steps as described on What happens when a package is installed, with the following additions:

  • The Console displays applicable license terms in its window with implied agreement. If you do not agree to the terms, you should uninstall the package immediately.
  • Also a reference to the package is added to the project file and appears in Solution Explorer under the References node, you need to save the project to see the changes in the project file directly.

Uninstall a package

See Uninstall-Package. Use Get-Package to see all packages currently installed in the default project if you need to find an identifier.

Uninstalling a package performs the following actions:

  • Removes references to the package from the project (and whatever management format is in use). References no longer appear in Solution Explorer. (You might need to rebuild the project to see it removed from the Bin folder.)
  • Reverses any changes made to app.config or web.config when the package was installed.
  • Removes previously-installed dependencies if no remaining packages use those dependencies.

Update a package

Find a package

See Find-Package. In Visual Studio 2013 and earlier, use Get-Package instead.

Читайте также:  Code blocks для linux

Availability of the console

Starting in Visual Studio 2017, NuGet and the NuGet Package Manager are automatically installed when you select any .NET-related workloads; you can also install it individually by checking the Individual components > Code tools > NuGet package manager option in the Visual Studio installer.

Also, if you’re missing the NuGet Package Manager in Visual Studio 2015 and earlier, check Tools > Extensions and Updates. and search for the NuGet Package Manager extension. If you’re unable to use the extensions installer in Visual Studio, you can download the extension directly from https://dist.nuget.org/index.html.

The Package Manager Console is not presently available with Visual Studio for Mac. The equivalent commands, however, are available through the NuGet CLI. Visual Studio for Mac does have a UI for managing NuGet packages. See Including a NuGet package in your project.

The Package Manager Console is not included with Visual Studio Code.

Extend the Package Manager Console

Some packages install new commands for the console. For example, MvcScaffolding creates commands like Scaffold shown below, which generates ASP.NET MVC controllers and views:

Set up a NuGet PowerShell profile

A PowerShell profile lets you make commonly-used commands available wherever you use PowerShell. NuGet supports a NuGet-specific profile typically found at the following location:

To find the profile, type $profile in the console:

Quickstart: Install and use a package in Visual Studio (Windows only)

NuGet packages contain reusable code that other developers make available to you for use in your projects. See What is NuGet? for background. Packages are installed into a Visual Studio project using the NuGet Package Manager, the Package Manager Console, or the dotnet CLI. This article demonstrates the process using the popular Newtonsoft.Json package and a Windows Presentation Foundation (WPF) project. The same process applies to any other .NET or .NET Core project.

Once installed, refer to the package in code with using where is specific to the package you’re using. Once the reference is made, you can call the package through its API.

Start with nuget.org: Browsing nuget.org is how .NET developers typically find components they can reuse in their own applications. You can search nuget.org directly or find and install packages within Visual Studio as shown in this article. For general information, see Find and evaluate NuGet packages.

Prerequisites

  • Visual Studio 2019 with the .NET Desktop Development workload.

You can install the 2019 Community edition for free from visualstudio.com or use the Professional or Enterprise editions.

Create a project

NuGet packages can be installed into any .NET project, provided that the package supports the same target framework as the project.

For this walkthrough, use a simple WPF app. Create a project in Visual Studio using File > New Project, typing .NET in the search box, and then selecting the WPF App (.NET Framework). Click Next. Accept the default values for Framework when prompted.

Visual Studio creates the project, which opens in Solution Explorer.

Add the Newtonsoft.Json NuGet package

To install the package, you can use either the NuGet Package Manager or the Package Manager Console. When you install a package, NuGet records the dependency in either your project file or a packages.config file (depending on the project format). For more information, see Package consumption overview and workflow.

NuGet Package Manager

In Solution Explorer, right-click References and choose Manage NuGet Packages.

Choose «nuget.org» as the Package source, select the Browse tab, search for Newtonsoft.Json, select that package in the list, and select Install:

If you want more information on the NuGet Package Manager, see Install and manage packages using Visual Studio.

Accept any license prompts.

(Visual Studio 2017 only) If prompted to select a package management format, select PackageReference in project file:

If prompted to review changes, select OK.

Package Manager Console

Select the Tools > NuGet Package Manager > Package Manager Console menu command.

Once the console opens, check that the Default project drop-down list shows the project into which you want to install the package. If you have a single project in the solution, it is already selected.

Enter the command Install-Package Newtonsoft.Json (see Install-Package). The console window shows output for the command. Errors typically indicate that the package isn’t compatible with the project’s target framework.

If you want more information on the Package Manager Console, see Install and manage packages using Package Manager Console.

Use the Newtonsoft.Json API in the app

With the Newtonsoft.Json package in the project, you can call its JsonConvert.SerializeObject method to convert an object to a human-readable string.

Open MainWindow.xaml and replace the existing Grid element with the following:

Open the MainWindow.xaml.cs file (located in Solution Explorer under the MainWindow.xaml node), and insert the following code inside the MainWindow class:

Even though you added the Newtonsoft.Json package to the project, red squiggles appears under JsonConvert because you need a using statement at the top of the code file:

Build and run the app by pressing F5 or selecting Debug > Start Debugging:

Select on the button to see the contents of the TextBlock replaced with some JSON text:

Find more NuGet videos on Channel 9 and YouTube.

Next steps

Congratulations on installing and using your first NuGet package!

To explore more that NuGet has to offer, select the links below.

Установка пакетов и управление ими с помощью консоли диспетчера пакетов в Visual Studio (PowerShell) Install and manage packages with the Package Manager Console in Visual Studio (PowerShell)

Консоль диспетчера пакетов NuGet позволяет использовать команды PowerShell NuGet для поиска, установки, удаления и обновления пакетов NuGet. The NuGet Package Manager Console lets you use NuGet PowerShell commands to find, install, uninstall, and update NuGet packages. Это удобно, когда пользовательский интерфейс диспетчера пакетов не позволяет выполнять операции. Using the console is necessary in cases where the Package Manager UI does not provide a way to perform an operation. См. подробнее об использовании CLI nuget.exe в консоли. To use nuget.exe CLI commands in the console, see Using the nuget.exe CLI in the console.

Читайте также:  Линукс запуск приложений для виндовс

Консоль встроена в Visual Studio для Windows. The console is built into Visual Studio on Windows. Она не включена в Visual Studio для Mac и Visual Studio Code. It is not included with Visual Studio for Mac or Visual Studio Code.

Перечисленные здесь команды относятся только к консоли диспетчера пакетов в Visual Studio и отличаются от команд модуля «Управление пакетами», доступных в общей среде PowerShell. The commands listed here are specific to the Package Manager Console in Visual Studio, and differ from the Package Management module commands that are available in a general PowerShell environment. В частности, в каждой среде есть команды, недоступные в другой среде, а в командах с тем же именем могут отличаться некоторые аргументы. Specifically, each environment has commands that are not available in the other, and commands with the same name may also differ in their specific arguments. При использовании консоли «Управление пакетами» в Visual Studio применяются команды и аргументы, описанные в этой статье. When using the Package Management Console in Visual Studio, the commands and arguments documented in this present topic apply.

Поиск и установка пакета Find and install a package

Для поиска и установки пакета необходимо выполнить три простых шага: For example, finding and installing a package is done with three easy steps:

Откройте проект или решение в Visual Studio, а затем откройте консоль, щелкнув Средства > Диспетчер пакетов NuGet > Консоль диспетчера пакетов. Open the project/solution in Visual Studio, and open the console using the Tools > NuGet Package Manager > Package Manager Console command.

Найдите пакет, который требуется установить. Find the package you want to install. Если вы уже знакомы с этим процессом, перейдите к шагу 3. If you already know this, skip to step 3.

Выполните команду установки: Run the install command:

Все операции, доступные в консоли, также можно выполнить с помощью CLI NuGet. All operations that are available in the console can also be done with the NuGet CLI. Но команды консоли работают в контексте Visual Studio и сохраненного проекта или решения, и область их применения часто шире, чем у их эквивалентов в CLI. However, console commands operate within the context of Visual Studio and a saved project/solution and often accomplish more than their equivalent CLI commands. Например, при установке пакета с помощью консоли добавляется ссылка на проект, а при использовании команды CLI этого не происходит. For example, installing a package through the console adds a reference to the project whereas the CLI command does not. По этой причине разработчики, работающие в Visual Studio, обычно предпочитают использовать консоль вместо CLI. For this reason, developers working in Visual Studio typically prefer using the console to the CLI.

Многие операции консоли зависят от наличия решения, открытого в Visual Studio с использованием известного имени пути. Many console operations depend on having a solution opened in Visual Studio with a known path name. Если у вас нет решения или оно не сохранено, отобразится сообщение об ошибке «Решение не открыто или не сохранено. If you have an unsaved solution, or no solution, you can see the error, «Solution is not opened or not saved. Убедитесь, что вы открыли и сохранили решение». Please ensure you have an open and saved solution.» Это означает, что консоль не может определить папку решения. This indicates that the console cannot determine the solution folder. Эту ошибку можно исправить, сохранив несохраненное решение или создав и сохранив решение, если оно не открыто. Saving an unsaved solution, or creating and saving a solution if you don’t have one open, should correct the error.

Открытие консоли и элементов управления консоли Opening the console and console controls

Откройте консоль в Visual Studio, щелкнув Средства > Диспетчер пакетов NuGet > Консоль диспетчера пакетов. Open the console in Visual Studio using the Tools > NuGet Package Manager > Package Manager Console command. Консоль — это окно Visual Studio, которое может быть упорядочено и размещено по вашему усмотрению (см. руководство по настройке макетов окон в Visual Studio). The console is a Visual Studio window that can be arranged and positioned however you like (see Customize window layouts in Visual Studio).

По умолчанию команды консоли работают с конкретным источником пакета и проектом, как указано в элементе управления в верхней части окна. By default, console commands operate against a specific package source and project as set in the control at the top of the window:

Выбор другого источника пакета или проекта изменяет эти значения по умолчанию для последующих команд. Selecting a different package source and/or project changes those defaults for subsequent commands. Чтобы переопределить эти настройки, не меняя значения по умолчанию, большинство команд поддерживают параметры -Source и -ProjectName . To overrride these settings without changing the defaults, most commands support -Source and -ProjectName options.

Чтобы управлять источниками пакетов, щелкните значок шестеренки. To manage package sources, select the gear icon. Это ярлык для диалогового окна Средства > Параметры > Диспетчер пакетов NuGet > Источники пакетов, как описано на странице, посвященной пользовательскому интерфейсу диспетчера пакетов. This is a shortcut to the Tools > Options > NuGet Package Manager > Package Sources dialog box as described on the Package Manager UI page. Кроме того, элемент управления справа от средства выбора проектов очищает содержимое консоли. Also, the control to the right of the project selector clears the console’s contents:

Читайте также:  Lenovo ideapad s145 не работает тачпад windows 10

Крайняя правая кнопка прерывает команду, которая выполняется в течение долгого периода времени. The rightmost button interrupts a long-running command. Например, выполнение Get-Package -ListAvailable -PageSize 500 перечисляет первые 500 пакетов в источнике по умолчанию (например, nuget.org), что может занять несколько минут. For example, running Get-Package -ListAvailable -PageSize 500 lists the top 500 packages on the default source (such as nuget.org), which could take several minutes to run.

Установка пакета Install a package

При установке пакета в консоли выполняются те же действия, которые описаны в руководстве по установке пакета NuGet, со следующими дополнениями: Installing a package in the console performs the same steps as described on What happens when a package is installed, with the following additions:

  • Консоль отображает применимые условия лицензии в окне с соответствующим соглашением. The Console displays applicable license terms in its window with implied agreement. Если вы не согласны с условиями, следует сразу же удалить пакет. If you do not agree to the terms, you should uninstall the package immediately.
  • Кроме того, ссылка на пакет добавляется в файл проекта и отображается в обозревателе решений в узле Ссылки. Сохраните проект, чтобы просмотреть изменения непосредственно в файле проекта. Also a reference to the package is added to the project file and appears in Solution Explorer under the References node, you need to save the project to see the changes in the project file directly.

Удаление пакета Uninstall a package

См. подробнее об Uninstall-Package. See Uninstall-Package. Если необходимо найти идентификатор, чтобы просмотреть все пакеты, установленные в проекте по умолчанию, используйте команду Get-Package. Use Get-Package to see all packages currently installed in the default project if you need to find an identifier.

При удалении пакета выполняются следующие действия: Uninstalling a package performs the following actions:

  • Удаляются ссылки на пакет из проекта (и любого используемого формата управления). Removes references to the package from the project (and whatever management format is in use). Ссылки больше не отображаются в обозревателе решений References no longer appear in Solution Explorer. (возможно, потребуется перестроить проект, чтобы он был удален из папки Bin). (You might need to rebuild the project to see it removed from the Bin folder.)
  • Отменяются все изменения, внесенные в app.config или web.config при установке пакета. Reverses any changes made to app.config or web.config when the package was installed.
  • Удаляются ранее установленные зависимости, если остальные пакеты не используют эти зависимости. Removes previously-installed dependencies if no remaining packages use those dependencies.

Обновление пакета Update a package

Поиск пакета Find a package

См. подробнее о Find-Package. See Find-Package. В Visual Studio 2013 и более ранних версиях используйте команду Get-Package. In Visual Studio 2013 and earlier, use Get-Package instead.

Доступность консоли Availability of the console

Начиная с Visual Studio 2017, NuGet и диспетчер пакетов NuGet автоматически устанавливаются при выборе рабочей нагрузки, связанной с .NET. Вы также можете установить эти компоненты отдельно, щелкнув Отдельные компоненты > Средства для работы с кодом > Диспетчер пакетов NuGet в установщике Visual Studio. Starting in Visual Studio 2017, NuGet and the NuGet Package Manager are automatically installed when you select any .NET-related workloads; you can also install it individually by checking the Individual components > Code tools > NuGet package manager option in the Visual Studio installer.

Кроме того, если у вас нет диспетчера пакетов NuGet в Visual Studio 2015 и более ранних версиях, щелкните Инструменты > Расширения и обновления и найдите расширение диспетчера пакетов NuGet. Also, if you’re missing the NuGet Package Manager in Visual Studio 2015 and earlier, check Tools > Extensions and Updates. and search for the NuGet Package Manager extension. Если вы не можете использовать установщик расширений в Visual Studio, скачайте расширение отсюда: https://dist.nuget.org/index.html. If you’re unable to use the extensions installer in Visual Studio, you can download the extension directly from https://dist.nuget.org/index.html.

Консоль диспетчера пакетов сейчас недоступна в Visual Studio для Mac. The Package Manager Console is not presently available with Visual Studio for Mac. Но аналогичные команды доступны через CLI NuGet. The equivalent commands, however, are available through the NuGet CLI. В Visual Studio для Mac есть пользовательский интерфейс для управления пакетами NuGet. Visual Studio for Mac does have a UI for managing NuGet packages. См. подробнее о включении пакета NuGet в проект. See Including a NuGet package in your project.

Консоль диспетчера пакетов не входит в Visual Studio Code. The Package Manager Console is not included with Visual Studio Code.

Расширение консоли диспетчера пакетов Extend the Package Manager Console

Некоторые пакеты устанавливают новые команды для консоли. Some packages install new commands for the console. Например, MvcScaffolding создает команды, например команду Scaffold (см. ниже), которая, в свою очередь, создает контроллеры и представления ASP.NET MVC. For example, MvcScaffolding creates commands like Scaffold shown below, which generates ASP.NET MVC controllers and views:

Настройка профиля PowerShell NuGet Set up a NuGet PowerShell profile

Профиль PowerShell позволяет сделать часто используемые команды доступными при использовании PowerShell. A PowerShell profile lets you make commonly-used commands available wherever you use PowerShell. NuGet поддерживает профиль NuGet, который обычно находится в следующем расположении: NuGet supports a NuGet-specific profile typically found at the following location:

Чтобы найти профиль, в консоли введите $profile . To find the profile, type $profile in the console:

Оцените статью