Перейти к содержимому

Как перенести visual studio на другой компьютер

  • автор:

Settings Sync

Settings Sync lets you share your Visual Studio Code configurations such as settings, keybindings, and installed extensions across your machines so you are always working with your favorite setup.

Turning on Settings Sync

You can turn on Settings Sync using the Turn On Settings Sync. entry in the Manage gear menu at the bottom of the Activity Bar.

Turn on Sync command

You will be asked to sign in and what preferences you would like to sync; currently Settings, Keyboard Shortcuts, Extensions, User Snippets, and UI State are supported.

Settings Sync configure dialog

Selecting the Sign in & Turn on button will ask you to choose between signing in with your Microsoft or GitHub account.

Settings Sync configure dialog

After making this selection, the browser will open so that you can sign in to your Microsoft or GitHub account. When a Microsoft account is chosen, you can use either personal accounts, such as Outlook accounts, or Azure accounts, and you can also link a GitHub account to a new or existing Microsoft account.

After signing in, Settings Sync will be turned on and continue to synchronize your preferences automatically in the background.

Merge or Replace

If you already synced from a machine and turning on sync from another machine, you will be shown with following Merge or Replace dialog.

Settings Sync Merge or Replace dialog

  • Merge: Selecting this option will merge local settings with remote settings from the cloud.
  • Replace Local: Selecting this option will overwrite local settings with remote settings from the cloud.
  • Merge Manually. : Selecting this option will open Merges view where you can merge preferences one by one.

Settings Sync Merges

Configuring synced data

Machine settings (with machine or machine-overridable scopes) are not synchronized by default, since their values are specific to a given machine. You can also add or remove settings you want to this list from the Settings editor or using the setting settingsSync.ignoredSettings .

Settings Sync ignored settings

Keyboard Shortcuts are synchronized per platform by default. If your keyboard shortcuts are platform-agnostic, you can synchronize them across platforms by disabling the setting settingsSync.keybindingsPerPlatform .

All built-in and installed extensions are synchronized along with their global enablement state. You can skip synchronizing an extension, either from the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ) or using the setting settingsSync.ignoredExtensions .

Settings Sync ignored settings

Following UI State is synchronized currently:

  • Display Language
  • Activity Bar entries
  • Panel entries
  • Views layout and visibility
  • Recently used commands
  • Do not show again notifications

You can always change what is synced via the Settings Sync: Configure command or by opening the Manage gear menu, selecting Settings Sync is On, and then Settings Sync: Configure.

Conflicts

When synchronizing settings between multiple machines, there may occasionally be conflicts. Conflicts can happen when first setting up sync between machines or when settings change while a machine is offline. When conflicts occur, you will be presented with the following options:

  • Accept Local: Selecting this option will overwrite remote settings in the cloud with your local settings.
  • Accept Remote: Selecting this option will overwrite local settings with remote settings from the cloud.
  • Show Conflicts: Selecting this will display a diff editor similar to the Source Control diff editor, where you can preview the local and remote settings and choose to either accept local or remote or manually resolve the changes in your local settings file and then accept the local file.

Switching Accounts

If at any time you want to sync your data to a different account, you can turn off and turn on Settings Sync again with different account.

Syncing Stable versus Insiders

By default, the VS Code Stable and Insiders builds use different Settings Sync services, and therefore do not share settings. You can sync your Insiders with Stable by selecting the Stable sync service while turning on Settings Sync. This option is only available in VS Code Insiders.

Settings Sync Switch Service

Note: Since Insiders builds are newer than Stable builds, syncing them can sometimes lead to data incompatibility. In such cases, Settings sync will be disabled automatically on stable to prevent data inconsistencies. Once newer version of Stable build is released, you can upgrade your stable client and turn on sync to continue syncing.

Restoring data

VS Code always stores local and remote backups of your preferences while syncing and provides views for accessing these. In case something goes wrong, you can restore your data from these views.

Settings Sync backup views

You can open these views using Settings Sync: Show Synced Data command from the Command Palette. The Local Sync activity view is hidden by default and you can enable it using Views submenu under Settings Sync view overflow actions.

Settings Sync enable local backup views

Local backups folder in the disk can be accessed via the Settings Sync: Open Local Backups Folder command. The folder is organized by the type of preference and contains versions of your JSON files, named with a timestamp of when the backup occurred.

Note: Local backups are automatically deleted after 30 days. For remote backups the latest 20 versions of each individual resource (settings, extensions, etc.) is retained.

Synced Machines

VS Code keeps track of the machines synchronizing your preferences and provides a view to access them. Every machine is given a default name based on the type of VS Code (Insiders or Stable) and the platform it is on. You can always update the machine name using the edit action available on the machine entry in the view. You can also disable sync on another machine using Turn off Settings Sync context menu action on the machine entry in the view.

Settings Sync machines views

You can open this view using Settings Sync: Show Synced Data command from the Command Palette.

Extension authors

If you are an extension author, you should make sure your extension behaves appropriately when users enable Setting Sync. For example, you probably don’t want your extension to display the same dismissed notifications or welcome pages on multiple machines.

Sync user global state between machines

If your extension needs to preserve some user state across different machines then provide the state to Settings Sync using vscode.ExtensionContext.globalState.setKeysForSync . Sharing state such as UI dismissed or viewed flags across machines can provide a better user experience.

There is an example of using setKeysforSync in the Extension Capabilities topic.

Reporting issues

Settings Sync activity can be monitored in the Log (Settings Sync) output view. If you experience a problem with Settings Sync, include this log when creating the issue. If your problem is related to authentication, also include the log from the Account output view.

How do I delete my data?

If you want to remove all your data from our servers, just turn off sync via Settings Sync is On menu available under Manage gear menu and select the checkbox to clear all cloud data. If you choose to re-enable sync, it will be as if you’re signing in for the first time.

Next steps

    — Learn how to configure VS Code to your preferences through user and workspace settings.

Common questions

Is VS Code Settings Sync the same as the Settings Sync extension?

No, the Settings Sync extension by Shan Khan uses a private Gist on GitHub to share your VS Code settings across different machines and is unrelated to the VS Code Settings Sync.

What types of accounts can I use for Settings Sync sign in?

VS Code Settings Sync supports signing in with either a Microsoft account (for example Outlook or Azure accounts) or a GitHub account. Sign in with GitHub Enterprise accounts is not supported. Other authentication providers may be supported in the future and you can review the proposed Authentication Provider API in issue #88309.

Can I use a different backend or service for Settings Sync?

Settings Sync uses a dedicated service to store settings and coordinate updates. A service provider API may be exposed in the future to allow for custom Settings Sync backends.

Troubleshooting keychain issues

Settings Sync persists authentication information to the system keychain. Writing to the keychain can fail in some cases if the keychain is misconfigured.

Windows

If the keychain throws the error "Not enough memory resources are available to process this command", open the Credential Manager application, click on Windows Credentials and go through the list to see if there are some you can delete. This error was first reported in issue #130893 and happens when you have too many credentials in your Credential Manager.

If you’re not sure what credentials to delete, try deleting all of the vscode specific credentials which all start with vscode . Here is a PowerShell one-liner that does exactly that:

For more troubleshooting steps, please refer to issue #130893.

macOS

If the keychain throws the error "The user name or passphrase you entered is not correct.", open the Keychain Access app, right-click on the login keychain, and lock and unlock it again. This error was first reported in issue #76 as a problem after upgrading to macOS High Sierra, but it has also been reported on more recent macOS versions.

Linux

If the keychain throws the error "No such interface "org.freedesktop.Secret.Collection" on object at path /org/freedesktop/secrets/collection/login", try following the steps described in issue #92972 to create a new keyring.

If the error is "Writing login information to the keychain failed with error ‘Unknown or unsupported transport “disabled” for address “disabled:”’", check that dbus-launch has been started by adding export $(dbus-launch) in your init-script. More info on issue #137850 & issue #120392.

If the error is "The name org.freedesktop.secrets was not provided by any .service files", make sure that you have a package that implements the Secret Storage API installed, such as gnome-keyring . VS Code expects such a package for storing credentials on the machine. More information can be found in issue #104319.

If the error is "Writing login information to the keychain failed with error ‘Cannot create an item in a locked collection’.", you need to:

Add the following lines to your

Have the following programs installed (installation assumes arch/pacman, should be similar to other distros):

Launch seahorse , unlock the default password keyring or create a new one, and keep it unlocked.

Restart the login procedure.

Can I share settings between VS Code Stable and Insiders?

Yes. Please refer to the Syncing Stable versus Insiders section for more information.

Please note that this can sometimes lead to data incompatibility because Insiders builds are newer than Stable builds. In such cases, Settings Sync will be disabled automatically on Stable to prevent data inconsistencies. Once a newer version of the Stable build is released, you can upgrade your client and turn on Settings Sync to continue syncing.

How can I export settings?

How is it possible to export all Visual Studio Code settings and plugins and import them to another machine?

Peter Mortensen's user avatar

kagarlickij's user avatar

13 Answers 13

With the current version of Visual Studio Code as of this writing (1.22.1), you can find your settings in:

The files are settings.json and keybindings.json . Simply copy them to the target machine.

Alternately, just go to the Extensions, show installed extensions, and install those on your target installation. For me, copying the extensions worked just fine, but it may be extension-specific, particularly if moving between platforms, depending on what the extension does.

wjandrea's user avatar

T.J. Crowder's user avatar

/.vscode/extensions and (2)

/.vscode/settings. Then I'd create symlinks to the paths in your answer according to the specific OS. Once it's done, I just put my

/ folder under version control. Like this, I keep my dotfiles and vscode config all in one repo.

/Library/Application Support/Code folder

There is an extension for Visual Studio Code, called Settings Sync.

It synchronises your settings by gist (Gist by GitHub). It works the same as the Atom.io extension called settings-sync.

UPDATE:

This feature is now build in VS Code, it is worth to switch to official feature. (https://stackoverflow.com/a/64035356/2029818)

You can now sync all your settings across devices with VSCode’s built-in Settings Sync. It’s found under Code > Preferences > Turn on Settings Sync.

Similar to the answer given by Big Rich you can do the following:

This will list out your extensions with the command to install them so you can just copy and paste the entire output into your other machine:

It is taken from the answer given here.

Note: Make sure you have added VS Code to your path beforehand. On mac you can do the following:

  1. Launch Visual Studio Code
  2. Open the Command Palette ( ⇧ + ⌘ + P ) and type ‘shell command’ to find the Shell Command: Install ‘code’ command in PATH command.

wjandrea's user avatar

Daniel Douglas's user avatar

For posterity, this post mentions,

in the latest release of Visual Studio Code (May 2016) it is now possible to list the installed extension in the command line

On Mac, execute something like:

Peter Mortensen's user avatar

You can now synchronise all your settings across devices with Visual Studio Code’s built-in Settings Sync. It’s found under menu FilePreferencesTurn on Settings Sync.

Read more about it in the official documentation here.

Peter Mortensen's user avatar

Ole August Støle's user avatar

Your user settings are in

If you’re not concerned about synchronising and it’s a one-time thing, you can just copy the files keybindings.json and settings.json to the corresponding folder on your new machine.

Your extensions are in the

/.vscode folder. Most extensions aren’t using any native bindings and they should be working properly when copied over. You can manually reinstall those who do not.

Peter Mortensen's user avatar

I’m preferred my own way to synchronize all Visual Studio Code extensions between laptops, using .dotfiles and small script to perform updates automatically. This way helps me every time when I want to install all extensions I have without any single mouse activity in Visual Studio Code after installing (via Homebrew).

So I just write each new added extension to .txt file stored at my .dotfiles folder. After that I pull master branch on another laptop to get up-to-date file with all extensions.

Using the script, which Big Rich had written before, with one more change, I can totally synchronise all extensions almost automatically.

Script

And also there is one more way to automate that process. Here you can add a script which looks up a Visual Studio Code extension in realtime and each time when you take a diff between the code —list-extensions command and your .txt file in .dotfiles , you can easily update your file and push it to your remote repository.

Peter Mortensen's user avatar

hamsternik's user avatar

I’ve made a Python script for exporting Visual Studio Code settings into a single ZIP file:

You can upload the ZIP file to external storage.

PS: You may implement the vsc-settings.py import subcommand for me.

Peter Mortensen's user avatar

This is my syncing configuration repo for VSCodium (for Linux only). If you use VSCode, just replace the codium with code and the syncing will be fine.

wjandrea's user avatar

Portable Mode instructs Visual Studio Code to store all its configuration and plugins in a specific directory (called data/ in Windows and Linux and code-portable-data in macOS).

At any time you could copy the data directory and copy it on another installation.

wjandrea's user avatar

VS Code provides 2 options to take care your settings. One is import/Export and other is Sync settings with github profile.

Follow below steps to Export VS code settings

Search for ‘Profiles: Export’ in the Command Palette (Ctrl+Shift+P). enter image description here

Select ‘what to export’ and confirm by clicking on ‘OK’ enter image description here

Name you export —

enter image description here

  1. Select Local file which will download file

enter image description here

To import, choose ‘Profiles: Import’ from Command Palette

Rohan Khude's user avatar

Often there are questions about the Java settings in Visual Studio Code. This is a big question and can involve advanced user knowledge to accomplish. But there is simple way to get the existing Java settings from Visual Studio Code and copy these setting for use on another PC. This post is using recent versions of Visual Studio Code and JDK in mid-December 2020.

There are several screen shots (below) that accompany this post which should provide enough information for the visual learners.

First things first, open Visual Studio Code and either open an existing Java folder-file or create a new Java file in Visual Studio Code. Then look at the lower right corner of Visual Studio Code (on the blue command bar). The Visual Studio Code should be displaying an icon showing the version of the Java Standard Edition (Java SE) being used. The version being on this PC today is JavaSE-15. (link 1)

Click on that icon ( JAVASE-15 ) which then opens a new window named " java.configuration.runtimes ". There should be two tabs below this name: User and Workspace . Below these tabs is a link named, " Edit in settings.json ". Click on that link. (Link 2)

Two json files should then open: Default settings and settings.json . This post only focuses on the " settings.json " file.

The settings.json file shows various settings used for coding different programming languages (Python, R, and Java). Near the bottom of the settings.json file shows the settings this User uses in Visual Studio Code for programming Java.

These Java settings are the settings that can be "backed up" — meaning these settings get copied and pasted to another PC for creating a Java programming environment similar to the Java programming environment on this PC. (Link 3)

Настройки импорта и экспорта в Visual Studio

Точно настроив интегрированную среду разработки по своему вкусу, вы можете сохранить эти настройки на будущее. Для этого можно экспортировать настройки интегрированной среды в файл или даже передать ряду инсталляций системы Visual Studio 2013, чтобы во всех установленных системах были одинаковые настройки.

Для того чтобы экспортировать выбранную конфигурацию, выберите команду Tools —> Import and Export Settings, чтобы запустить мастер Import and Export Settings Wizard, как показано на рисунке ниже. На первом этапе работы этого мастера следует выбрать настройку Export, а также настройки, которые следует сохранить при выполнении процедуры экспорта.

Импорт/экспорт настроек среды Visual Studio

Как показано на рисунке, можно экспортировать множество сгруппированных настроек. На этом снимке экрана видно, как раскрывается раздел Options, демонстрируя, что следует сохранить настройки Debugging и Projects, а также конфигурации Text Editor и Windows Forms Designer. Маленькие пиктограммы с восклицательным знаком свидетельствуют о том, что некоторые настройки не были предназначены для экспорта по умолчанию, поскольку они содержат информацию, которая может нарушить конфиденциальность информации. В этом разделе вы должны сделать свой выбор вручную, если действительно хотите, чтобы эта информация была сохранена в резервном файле. Выбрав настройки, которые хотите экспортировать, переходите к следующему этапу работы мастера, который может занять несколько минут, в зависимости от того, сколько настроек вы экспортируете.

Импортировать файл настроек очень легко. Для этого используется тот же самый мастер, но теперь на первом этапе вам следует выбрать команду Import. Вместо простой перезаписи текущей конфигурации мастер позволяет вам сначала сохранить резервную копию текущих настроек.

Затем можете выбрать существующий файл конфигурации из списка. Это тот же самый список файлов, из которого вы выбираете настройки при первом запуске системы Visual Studio 2013. Кроме того, можете просмотреть файлы настроек, созданные вами заранее. Выбрав файл настроек, можете импортировать только разделы конфигурации или всю ее целиком.

Мастер по умолчанию исключает несколько разделов, таких как External Tools или Command Aliases, чтобы вы не могли непреднамеренно уничтожить пользовательские настройки. Убедитесь, что вы выбрали эти разделы, если хотите восстановить все настройки.

Если вы просто хотите восстановить одну из конфигураций системы Visual Studio 2013, заданных по умолчанию, выполните команду Reset All Settings на первом этапе работы мастера и не выполняйте весь процесс импорта.

Visual Studio предоставляет возможность поделиться настройками с членами команды, с которой вы работаете. Это полезно в тех случаях, например, когда происходит редактирование одних и тех же файлов (используя Team Foundation Server). Каждый программист по своему оформляет код, использует символы табуляции и т.д. Когда разные члены команды работают с одним файлом, простое редактирование файла может привести к незначительным изменениям, не влияющим на работу приложения (лишние пробелы, переносы строк и т.д.) Однако, когда эти файлы добавляются в репозиторий исходного кода (TFS, Git, . ), эти изменения могут вызвать проблемы.

Если вы работаете с командой разработчиков, создание единого файла настроек является хорошей идеей. В разделе настроек Environment —> Import and Export Settings вы можете установить флажок Use Team Settings File:

Импорт настроек Visual Studio для команды разработчиков

Когда этот флажок установлен, должен быть указан путь, где будет храниться общий файл настроек.

Настройки синхронизации

Одним из нововведений среды Visual Studio 2013 является ее синхронизация с облачными службами. Вы можете войти в Visual Studio с учетной записью Microsoft и настройки Visual Studio будут синхронизированы на всех ваших компьютерах. Этот процесс синхронизации не распространяется на все настройки Visual Studio. При отсутствии дополнительных настроек с вашей стороны, синхронизация затрагивает следующие параметры:

Настройки разработчика (это те параметры, которые были указаны при установке Visual Studio и первом ее запуске).

Настройка цветовой темы (Environment —> General)

Настройки шрифтов и цвета (Environment —> Fonts and Colors)

Горячие клавиши (Environment —> Keyboard )

Параметры запуска (Environment —> Startup)

Настройки текстового редактора (Text Editor)

Все пользовательские псевдонимы команд

Можно изменить настройки синхронизации или вообще полностью выключить. Для этого, в диалоговом окне Options выберете узел Environment —> Synchronized Settings, где можно увидеть уровень детализации, доступный для вас. Чтобы полностью отключить синхронизацию, убедитесь, что флажок включения синхронизации не установлен для всех категорий параметров.

Настройки синхронизации в Visual Studio

Итак, ранее были изложены лишь основные сведения о выборе полезных настроек, позволяющих вам настроить интерфейс системы Visual Studio по своему вкусу; кроме этого вам доступно много других возможностей. Эти многочисленные настройки позволяют настраивать редактирование кода, добавлять элементы управления в вашу форму и даже выбирать методы при отладке кода. Настройки, доступные в диалоговом окне Options, также позволяют вам управлять процессом создания приложений и даже задавать собственные комбинации клавиш для выполнения команд. Позже мы будем еще не раз обращаться к диалоговому окну Options для настройки процессов компиляции, отладки и написания макросов.

Копирование / перемещение проектов / решений Visual Studio на другой компьютер

Итак, у меня есть несколько проектов Visual Studio, которые мне нужно перенести на другой компьютер. Это так просто, как скопировать и вставить, или это что-то испортит? На обеих машинах будет установлена ​​одна и та же версия Visual Studio, так что это не должно быть проблемой.

Есть ли функция экспорта, которую я упустил?

4 ответа

Если версия Visual Studio такая же, вы можете просто скопировать папку проекта.

Пока вы перемещаете файл решения и связанные с ним файлы, вы должны быть в порядке.

Если вы используете какой-либо источник контроля, обновите свое решение оттуда.

Надеюсь, у вас такая же версия VS и любые фреймворки аддонов

Можете ли вы сохранить файл в облаке? если да, то вы потенциально можете загрузить файл в облако и загрузить файл в новый

Вы можете напрямую скопировать проект в папку проектов. Для меня это отлично сработало для проектов Visual C ++ (а также для некоторых других проектов). Но когда я скопировал свое приложение Cordova с одного компьютера на другой (на обоих была Visual Studio 2015), я не смог открыть проект. Всякий раз, когда я пытался открыть проект, пробуя оба способа — непосредственно из файла проекта и опции открытия в Visual Studio, он сначала открывался, но когда я пытался открыть файл, он просто зависал и не отвечал.

Эта проблема может возникнуть из-за того, что в приложениях Cordova есть файлы конфигурации, которые могут отличаться для разных компьютеров. Я не уверен, что это причина проблемы.

Решение, которое я использовал, заключалось в том, что я создал новый проект и скопировал файлы в папки проекта (за исключением файлов конфигурации).

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *