Как открыть консоль в визуал студио
Перейти к содержимому

Как открыть консоль в визуал студио

  • автор:

C# Language учебник
Начало работы с C # Language

C # — это мультипарадигма, язык программирования C-потомок от Microsoft. C # — управляемый язык, который компилируется в CIL , промежуточный байт-код, который может быть выполнен в Windows, Mac OS X и Linux.

Версии 1.0, 2.0 и 5.0 были стандартизованы ECMA (как ECMA-334 ), и в настоящее время предпринимаются усилия по стандартизации для современного C #.

Версии

Версия Дата выхода
1,0 2002-01-01
1.2 2003-04-01
2,0 2005-09-01
3.0 2007-08-01
4,0 2010-04-01
5.0 2013-06-01
6,0 2015-07-01
7,0 2017-03-07

Создание нового консольного приложения (Visual Studio)

  1. Открыть Visual Studio
  2. На панели инструментов перейдите в ФайлНовый проект
  3. Выберите тип проекта консоли.
  4. Откройте файл Program.cs в обозревателе решений
  5. Добавьте следующий код в Main() :
  1. На панели инструментов нажмите « Отладка» -> « Начать отладки» или нажмите « F5» или « Ctrl + F5» (работает без отладчика), чтобы запустить программу.

объяснение

class Program — это объявление класса. Класс Program содержит определение данных и методов , которые используются в вашей программе. Классы обычно содержат несколько методов. Методы определяют поведение класса. Однако класс Program имеет только один метод: Main .

static void Main() определяет метод Main , который является точкой входа для всех программ на C #. Main метод определяет, что делает класс при выполнении. Для каждого класса допускается только один Main метод.

System.Console.WriteLine("Hello, world!"); метод выводит данные (в этом примере, Hello, world! ) в качестве вывода в окне консоли.

System.Console.ReadKey() , гарантирует, что программа не будет закрываться сразу после отображения сообщения. Он делает это, ожидая, что пользователь нажмет клавишу на клавиатуре. Любое нажатие клавиши от пользователя прекратит выполнение программы. Программа завершается, когда она закончила последнюю строку кода в методе main() .

Использование командной строки

Для компиляции с помощью командной строки используйте либо MSBuild либо csc.exe (компилятор C #) , как часть пакета средств Microsoft Build Tools .

Чтобы скомпилировать этот пример, запустите следующую команду в том же каталоге, где находится HelloWorld.cs :

Также возможно, что у вас есть два основных метода внутри одного приложения. В этом случае, вы должны сообщить компилятору, основной метод , чтобы выполнить, введя следующую команду в консоли. (Предположит , что класс ClassA также имеет основной метод в том же HelloWorld.cs файл HelloWorld имен)

где HelloWorld — пространство имен

Примечание . Это путь, в котором .NET framework v4.0 находится в целом. Измените путь в соответствии с вашей версией .NET. Кроме того, каталог может быть фреймворком вместо framework64, если вы используете 32-разрядную .NET Framework. В командной строке Windows вы можете перечислить все пути csc.exe Framework, выполнив следующие команды (первая для 32-разрядных фреймворков):

Компиляция файла .cs

В этом же каталоге должен быть исполняемый файл HelloWorld.exe . Чтобы выполнить программу из командной строки, просто введите имя исполняемого файла и нажмите Enter следующим образом:

Выполнение exe-файла в консоли

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

Запуск исполняемого файла и использование двойного щелчка

Создание нового проекта в Visual Studio (консольное приложение) и запуск его в режиме отладки

Загрузите и установите Visual Studio . Visual Studio можно загрузить с сайта VisualStudio.com . Издание сообщества предлагается, во-первых, потому что оно бесплатное и второе, потому что оно включает в себя все общие функции и может быть расширено дальше.

Откройте Visual Studio.

Добро пожаловать. Откройте Файл → Новый → Проект . Microsoft Visual Studio - меню файлов

Нажмите ШаблоныVisual C #Консольное приложение

Microsoft Visual Studio - окно нового проекта

Выбрав консольное приложение, введите имя для своего проекта и место для сохранения и нажмите OK . Не беспокойтесь о имени решения.

Создан проект . Созданный проект будет выглядеть примерно так:

Microsoft Visual Studio - проект по умолчанию c #

(Всегда используйте описательные имена для проектов, чтобы их можно было легко отличить от других проектов. Рекомендуется не использовать пробелы в имени проекта или класса).

Напишите код. Теперь вы можете обновить программу Program.cs чтобы представить «Hello world!». для пользователя.

Добавьте следующие две строки в объект public static void Main(string[] args) в Program.cs : (убедитесь, что он находится внутри фигурных скобок)

Почему Console.Read() ? Первая строка выводит текст «Привет мир!». на консоль, а вторая строка ожидает ввода одного символа; по сути, это заставляет программу приостанавливать выполнение, чтобы вы могли видеть вывод во время отладки. Без Console.Read(); , когда вы начнете отлаживать приложение, оно просто напечатает «Hello world!». на консоль, а затем сразу же закрыть. Окно вашего кода теперь должно выглядеть следующим образом:

Отлаживайте свою программу. Нажмите кнопку «Пуск» на панели инструментов в верхней части окна. Кнопка запуска отладки или нажмите F5 на клавиатуре, чтобы запустить приложение. Если кнопки нет, вы можете запустить программу из главного меню: Debug → Start Debugging . Программа скомпилирует и откроет окно консоли. Он должен выглядеть примерно так, как показано на следующем снимке экрана:

Консоль, запускающая приложение Hello World

  1. Остановите программу. Чтобы закрыть программу, просто нажмите любую клавишу на клавиатуре. Добавленный нами Console.Read() был для этой же цели. Другой способ закрыть программу — это перейти в меню, где была кнопка « Пуск» , и нажать кнопку « Стоп» .

Создание новой программы с использованием Mono

Сначала установите Mono , выполнив инструкции по установке для выбранной вами платформы, как описано в разделе их установки .

Моно доступно для Mac OS X, Windows и Linux.

После завершения установки создайте текстовый файл, назовите его HelloWorld.cs и скопируйте в него следующий контент:

Если вы используете Windows, запустите Mono Command Prompt, которая включена в установку Mono, и убедитесь, что установлены необходимые переменные среды. Если на Mac или Linux откройте новый терминал.

Чтобы скомпилировать вновь созданный файл, запустите следующую команду в каталоге, содержащем HelloWorld.cs :

Получаемый HelloWorld.exe можно выполнить с помощью:

который будет производить выход:

Создание новой программы с использованием .NET Core

Сначала установите .NET Core SDK , выполнив инструкции по установке для выбранной вами платформы:

  • Windows
  • OSX
  • Linux
  • докер

По завершении установки откройте командную строку или окно терминала.

Создайте новый каталог с mkdir hello_world и перейдите во вновь созданный каталог cd hello_world .

Создайте новое консольное приложение с dotnet new console .
Это создаст два файла:

hello_world.csproj

Program.cs

Восстановите необходимые пакеты с dotnet restore .

Необязательно Создайте приложение с dotnet build для dotnet build Debug или dotnet build -c Release for Release. dotnet run также запускает компилятор и dotnet run ошибки сборки, если они есть.

Запустите приложение с dotnet run для dotnet run Debug или dotnet run .\bin\Release\netcoreapp1.1\hello_world.dll для выпуска.

Вывод командной строки

введите описание изображения здесь

Создание нового запроса с использованием LinqPad

LinqPad — отличный инструмент, который позволяет вам изучать и тестировать функции .Net-языков (C #, F # и VB.Net.)

Создайте новый запрос ( Ctrl + N ) введите описание изображения здесь

Под языком выберите «Операторы C #», введите описание изображения здесь

Введите следующий код и нажмите пробег ( F5 )

введите описание изображения здесь

  1. На экране результатов вы увидите «Hello World». введите описание изображения здесь
  2. Теперь, когда вы создали свою первую .Net-программу, пойдите и проверьте образцы, включенные в LinqPad, через браузер «Образцы». Есть много замечательных примеров, которые покажут вам много разных особенностей языков .Net. введите описание изображения здесь

Заметки:

  1. Если вы нажмете «IL», вы можете проверить код IL, который генерирует ваш .net-код. Это отличный инструмент обучения. введите описание изображения здесь
  2. При использовании LINQ to SQL или Linq to Entities вы можете проверить создаваемый SQL, что является еще одним отличным способом узнать о LINQ.

Command Line Interface (CLI)

Visual Studio Code has a powerful command-line interface built-in that lets you control how you launch the editor. You can open files, install extensions, change the display language, and output diagnostics through command-line options (switches).

command line example

If you are looking for how to run command-line tools inside VS Code, see the Integrated Terminal.

Command line help

To get an overview of the VS Code command-line interface, open a terminal or command prompt and type code —help . You will see the version, usage example, and list of command line options.

command line help

Launching from command line

You can launch VS Code from the command line to quickly open a file, folder, or project. Typically, you open VS Code within the context of a folder. To do this, from an open terminal or command prompt, navigate to your project folder and type code . :

launch VS Code

Note: Users on macOS must first run a command (Shell Command: Install ‘code’ command in PATH) to add VS Code executable to the PATH environment variable. Read the macOS setup guide for help.

Windows and Linux installations should add the VS Code binaries location to your system path. If this isn’t the case, you can manually add the location to the Path environment variable ( $PATH on Linux). For example, on Windows, VS Code is installed under AppData\Local\Programs\Microsoft VS Code\bin . To review platform-specific setup instructions, see Setup.

Insiders: If you are using the VS Code Insiders preview, you launch your Insiders build with code-insiders .

Core CLI options

Here are optional arguments you can use when starting VS Code at the command line via code :

Argument Description
-h or —help Print usage
-v or —version Print VS Code version (for example, 1.22.2), GitHub commit ID, and architecture (for example, x64).
-n or —new-window Opens a new session of VS Code instead of restoring the previous session (default).
-r or —reuse-window Forces opening a file or folder in the last active window.
-g or —goto When used with file:line , opens a file at a specific line and optional character position. This argument is provided since some operating systems permit : in a file name.
-d or —diff <file1> <file2> Open a file difference editor. Requires two file paths as arguments.
-m or —merge <path1> <path2> <base> <result> Perform a three-way merge by providing paths for two modified versions of a file, the common origin of both modified versions, and the output file to save merge results.
-w or —wait Wait for the files to be closed before returning.
—locale <locale> Set the display language (locale) for the VS Code session. (for example, en-US or zh-TW )

launch with locale

Opening Files and Folders

Sometimes you will want to open or create a file. If the specified file does not exist, VS Code will create them for you along with any new intermediate folders:

For both files and folders, you can use absolute or relative paths. Relative paths are relative to the current directory of the command prompt where you run code .

If you specify more than one file at the command line, VS Code will open only a single instance.

If you specify more than one folder at the command line, VS Code will create a Multi-root Workspace including each folder.

Argument Description
file Name of a file to open. If the file doesn’t exist, it will be created and marked as edited. You can specify multiple files by separating each file name with a space.
file:line[:character] Used with the -g argument. Name of a file to open at the specified line and optional character position.
folder Name of a folder to open. You can specify multiple folders and a new Multi-root Workspace is created.

go to line and column

Select a profile

You can launch VS Code with a specific profile via the —profile command-line interface option. You pass the name of the profile after the —profile argument and open a folder or a workspace using that profile. The command line below opens the web-sample folder with the "Web Development" profile:

/projects/web-sample —profile "Web Development"

If the profile specified does not exist, a new empty profile with the given name is created.

Working with extensions

You can install and manage VS Code extensions from the command line.

Argument Description
—install-extension <ext> Install an extension. Provide the full extension name publisher.extension as an argument. Use —force argument to avoid prompts.
—uninstall-extension <ext> Uninstall an extension. Provide the full extension name publisher.extension as an argument.
—disable-extensions Disable all installed extensions. Extensions will still be visible in the Disabled section of the Extensions view but they will never be activated.
—list-extensions List the installed extensions.
—show-versions Show versions of installed extensions, when using —list-extensions
—enable-proposed-api <ext> Enables proposed api features for an extension. Provide the full extension name publisher.extension as an argument.

install extension

Advanced CLI options

There are several CLI options that help with reproducing errors and advanced setup.

Argument Description
—extensions-dir <dir> Set the root path for extensions. Has no effect in Portable Mode.
—user-data-dir <dir> Specifies the directory that user data is kept in, useful when running as root. Has no effect in Portable Mode.
-s, —status Print process usage and diagnostics information.
-p, —performance Start with the Developer: Startup Performance command enabled.
—disable-gpu Disable GPU hardware acceleration.
—verbose Print verbose output (implies —wait ).
—prof-startup Run CPU profiler during startup.
—upload-logs Uploads logs from current session to a secure endpoint.
Multi-root
—add <dir> Add folder(s) to the last active window for a multi-root workspace.

Create remote tunnel

VS Code integrates with other remote environments to become even more powerful and flexible. Our goal is to provide a cohesive experience that allows you to manage both local and remote machines from one, unified CLI.

The Visual Studio Code Remote — Tunnels extension lets you connect to a remote machine, like a desktop PC or VM, via a secure tunnel. Tunneling securely transmits data from one network to another. You can then securely connect to that machine from anywhere, without the requirement of SSH.

We’ve built functionality into the code CLI that will initiate tunnels on remote machines. You can run:

to create a tunnel on your remote machine. You may connect to this machine through a web or desktop VS Code client.

You can review the other tunneling commands by running code tunnel -help :

Output of tunnel help CLI command

As you may need to run the CLI on a remote machine that can’t install VS Code Desktop, the CLI is also available for standalone install on the VS Code download page.

For more information on Remote Tunnels, you can review the Remote Tunnels documentation.

Opening VS Code with URLs

You can also open projects and files using the platform’s URL handling mechanism. Use the following URL formats to:

Open a file to line and column

You can use the URL in applications such as browsers or file explorers that can parse and redirect the URL. For example, on Windows, you could pass a vscode:// URL directly to the Windows Explorer or to the command line as start vscode:// .

vscode url in Windows Explorer

Note: If you are using VS Code Insiders builds, the URL prefix is vscode-insiders:// .

Next steps

Read on to find out about:

    — Run command-line tools from inside VS Code. — Learn the basics of the VS Code editor. — VS Code lets you quickly understand and move through your source code.

Common questions

‘code’ is not recognized as an internal or external command

Your OS cannot find the VS Code binary code on its path. The VS Code Windows and Linux installations should have installed VS Code on your path. Try uninstalling and reinstalling VS Code. If code is still not found, consult the platform-specific setup topics for Windows and Linux.

On macOS, you need to manually run the Shell Command: Install ‘code’ command in PATH command (available through the Command Palette ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ). Consult the macOS specific setup topic for details.

How do I get access to a command line (terminal) from within VS Code?

VS Code has an Integrated Terminal where you can run command-line tools from within VS Code.

Can I specify the settings location for VS Code in order to have a portable version?

Not directly through the command line, but VS Code has a Portable Mode, which lets you keep settings and data in the same location as your installation, for example, on a USB drive.

How do I detect when a shell was launched by VS Code?

When VS Code starts up, it may launch a shell in order to source the "shell environment" to help set up tools. This will launch an interactive login shell and fetch its environment. Depending on your shell setup, this may cause problems. For example, it may be unexpected that the shell is launched as an interactive session, which VS Code needs in order to try to align $PATH with the exact value in a user created terminal.

Whenever VS Code launches this initial shell, VS Code sets the variable VSCODE_RESOLVING_ENVIRONMENT to 1 . If your shell or user scripts need to know if they are being run in the context of this shell, you can check the VSCODE_RESOLVING_ENVIRONMENT value.

How can I open the terminal in Visual Studio?

How can I open the terminal for executing shell commands in Visual Studio (Community Edition)?

Peter Mortensen's user avatar

Xen_mar's user avatar

13 Answers 13

Visual Studio 2022/2019

Now Visual Studio has a built-in terminal:

Terminal SS

To change the default terminal

Menu ToolsOptionsTerminalSet As Default

Enter image description here

Before Visual Studio 2019

From comments, the best answer is from Hans Passant.

Add an external tool.

Menu ToolsExternal ToolsAdd

Title: Terminal (or name it yourself)

Command = cmd.exe or Command = powershell.exe

Initial Directory = $(ProjectDir)

Menu ToolsTerminal (or whatever you put in title)

Ali Karaca's user avatar

You can have an integrated terminal inside Visual Studio using one of these extensions:

Whack Whack Terminal

Terminal: CMD or PowerShell

Shortcut: Ctrl + \ , Ctrl + \

Supports: Visual Studio 2017

Whack Whack Terminal

BuiltinCmd

Terminal: CMD or PowerShell

Shortcut: Ctrl Shift T

Supports: Visual Studio 2013, 2015, 2017, and 2019

BuiltinCmd

Marcos's user avatar

As a tricky solution, you can use Package Manager Console to execute CMD or PowerShell commands.

Shortcut for Package Manager Console: Alt + T , + N , O

Tested on Visual Studio 2017 Community version.

Enter image description here

The shortcut is Ctrl + ` , the same as Visual Studio Code.

Peter Mortensen's user avatar

GOOD NEWS! Now, Visual studio has built-in terminal. In visual studio 2022 (and latest vs2019), We can open terminal from View > Terminal

open terminal in vs2022

In Visual Studio 2019, you can open Command/PowerShell window from menu ToolsCommand Line:

Enter image description here

If you want an integrated terminal, try
BuiltinCmd:

Enter image description here

You can also try WhackWhackTerminal (does not support Visual Studio 2019 by this date).

How to launch the terminal inside Visual Studio

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

Microsoft Visual Studio is a powerful and feature-packed IDE from Microsoft with tons of features to enhance developer productivity. It supports the launch of multiple command Shells and PowerShell terminals inside Visual Studio itself as a tab. This means that you don’t have to switch between various windows to work with multiple shells.

How to open the terminal in Visual Studio

We can use any one of the following ways to open the terminal:

  • Select the View Menu > Terminal option to launch the terminal as a Tab in Visual Studio.

A faster way to launch the terminal is to use the default keyboard shortcut Ctrl +` tilde or backquote key .

We can use the context menu from the Solution Explorer to open the terminal at a specific file path. For this, we select the folder in the Solution Explorer window and right-click and select the Open in Terminal option to open the context menu.

Terminal settings

If you launch the terminal, it automatically opens an integrated PowerShell instance. However, you can set up shell profiles to customize this startup experience. This can target different types of shells like a command shell, PowerShell, or any custom shell, and use different arguments to invoke them.

You can also set a shell as your default terminal: Go to Terminal Window > Settings and select the Set as default option after you choose from a list of available shells.

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

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