Command-Line Interface (CLI) Tools
The .NET CLI is a cross-platform toolchain that enables you to build, test, run, and publish .NET applications from the command line.
Getting Started with the .NET CLI
The .NET CLI is installed as part of the .NET SDK. To verify your installation, open your terminal or command prompt and run:
dotnet --version
This will output the version of the .NET SDK you have installed.
Common .NET CLI Commands
Creating Projects
Use the dotnet new command to create new .NET projects from templates.
- Create a console application:
dotnet new console -o MyConsoleApp - Create a class library:
dotnet new classlib -o MyLib - Create an ASP.NET Core web application:
dotnet new webapp -o MyWebApp
Building Projects
The dotnet build command compiles your project.
dotnet build
This command looks for a project file (e.g., .csproj) in the current directory and builds it.
Running Projects
Use dotnet run to compile and run your application.
dotnet run
This is useful for development and testing.
Restoring Dependencies
Before building or running, you often need to restore project dependencies:
dotnet restore
This command restores packages and other dependencies specified in the project file.
Publishing Applications
To create a self-contained deployment or a framework-dependent deployment, use dotnet publish.
- Framework-dependent deployment:
dotnet publish -c Release - Self-contained deployment (Windows x64):
dotnet publish -c Release -r win-x64 --self-contained false
The -c Release flag optimizes the build for release, and -r specifies the runtime identifier.
Testing Projects
Run tests with the dotnet test command.
dotnet test
This command discovers and runs unit tests from the specified project.
Working with Project Files (.csproj)
Project files define the structure, dependencies, and build configurations of your .NET project. They are written in XML.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
</ItemGroup>
</Project>
Key Elements:
<Project Sdk="...">: Specifies the SDK used for the project.<PropertyGroup>: Contains properties likeTargetFramework,OutputType, etc.<ItemGroup>: Groups related items likePackageReferencefor NuGet packages.
Customizing the Build
You can customize build behavior using properties in your .csproj file or by passing arguments to the CLI commands.
Important Note
Always ensure you are in the correct directory containing your project file (e.g., .csproj) when running .NET CLI commands.
Additional Resources
- dotnet new Command
- dotnet build Command
- dotnet run Command
- Migrating from project.json (for older .NET Core versions)