Skip to main content

Basic .NET CLI Commands: Master Your Development Workflow

The .NET Command Line Interface (CLI) is a powerful, cross-platform toolchain for developing .NET applications. Whether you're building web APIs, console applications, or complex enterprise solutions, mastering the .NET CLI will significantly boost your productivity. This guide covers all essential commands with practical examples.

What is the .NET CLI?

The .NET CLI is a command-line interface that provides essential functionality for .NET development:

  • Project Management: Create, build, and run projects
  • Package Management: Install and manage NuGet packages
  • Testing: Run unit tests and generate coverage reports
  • Publishing: Deploy applications for production
  • Tool Management: Install and manage .NET tools

Why Use the CLI?

  • Cross-Platform: Works on Windows, macOS, and Linux
  • IDE Independent: Works with any text editor or IDE
  • Automation: Perfect for CI/CD pipelines
  • Lightweight: Fast and efficient
  • Scriptable: Easy to automate with scripts

Installation and Setup

Installing .NET SDK

# Check if .NET is already installed
dotnet --version
dotnet --info

# Download from: https://dotnet.microsoft.com/download
# Or use package managers:

# Windows (using Chocolatey)
choco install dotnet

# macOS (using Homebrew)
brew install --cask dotnet

# Ubuntu/Debian
sudo apt-get update
sudo apt-get install -y dotnet-sdk-8.0

CLI Structure

All .NET CLI commands follow this pattern:

dotnet [command] [arguments] [options]

Get help for any command:

dotnet --help
dotnet new --help
dotnet build --help

Project Creation and Templates

Creating New Projects

The dotnet new command creates projects from templates:

# List available templates
dotnet new list

# Create different project types
dotnet new console -n MyConsoleApp # Console application
dotnet new webapp -n MyWebApp # Web application
dotnet new webapi -n MyApi # Web API
dotnet new classlib -n MyLibrary # Class library
dotnet new xunit -n MyTests # Unit test project
dotnet new blazorserver -n MyBlazorApp # Blazor server app
dotnet new mvc -n MyMvcApp # MVC application

Working with Solutions

Manage multiple projects with solutions:

# Create a new solution
dotnet new sln -n MySolution

# Add projects to solution
dotnet sln add src/MyApi/MyApi.csproj
dotnet sln add src/MyLibrary/MyLibrary.csproj
dotnet sln add tests/MyTests/MyTests.csproj

# List projects in solution
dotnet sln list

# Remove project from solution
dotnet sln remove tests/MyTests/MyTests.csproj

Project References

Manage dependencies between projects:

# Add project reference
dotnet add reference ../MyLibrary/MyLibrary.csproj

# Add multiple references
dotnet add reference ../LibraryA/LibraryA.csproj ../LibraryB/LibraryB.csproj

# Remove reference
dotnet remove reference ../MyLibrary/MyLibrary.csproj

# List references
dotnet list reference

Building and Running Applications

Building Projects

# Build current project
dotnet build

# Build specific project
dotnet build MyProject.csproj

# Build entire solution
dotnet build MySolution.sln

# Build with specific configuration
dotnet build --configuration Release
dotnet build --configuration Debug

# Build with additional options
dotnet build --verbosity normal
dotnet build --no-restore # Skip package restore
dotnet build --output ./bin/ # Specify output directory

Running Applications

# Run current project
dotnet run

# Run with arguments
dotnet run -- arg1 arg2 arg3

# Run specific project
dotnet run --project src/MyApi/MyApi.csproj

# Run with environment variables
ASPNETCORE_ENVIRONMENT=Development dotnet run

# Run with specific configuration
dotnet run --configuration Release

# Watch for changes and auto-restart (great for development)
dotnet watch run

Restore Dependencies

# Restore packages for current project
dotnet restore

# Restore packages for solution
dotnet restore MySolution.sln

# Restore with specific source
dotnet restore --source https://api.nuget.org/v3/index.json

# Restore and ignore cache
dotnet restore --no-cache

# Restore for specific runtime
dotnet restore --runtime win-x64

Package Management

Adding NuGet Packages

# Add package (latest version)
dotnet add package Newtonsoft.Json

# Add specific version
dotnet add package Newtonsoft.Json --version 13.0.3

# Add prerelease package
dotnet add package Microsoft.Extensions.Hosting --prerelease

# Add package from specific source
dotnet add package MyPackage --source https://my-private-feed.com/nuget

# Add package to specific project
dotnet add src/MyApi/MyApi.csproj package Serilog

Managing Packages

# List installed packages
dotnet list package

# List packages with outdated versions
dotnet list package --outdated

# List packages with vulnerabilities
dotnet list package --vulnerable

# Update packages
dotnet add package Newtonsoft.Json # Updates to latest version

# Remove package
dotnet remove package Newtonsoft.Json

Package Sources

# List configured package sources
dotnet nuget list source

# Add package source
dotnet nuget add source https://my-private-feed.com/nuget --name PrivateFeed

# Remove package source
dotnet nuget remove source PrivateFeed

# Enable/disable source
dotnet nuget enable source PrivateFeed
dotnet nuget disable source PrivateFeed

Testing

Running Tests

# Run all tests
dotnet test

# Run tests in specific project
dotnet test tests/MyTests/MyTests.csproj

# Run tests with detailed output
dotnet test --verbosity normal

# Run tests and collect coverage
dotnet test --collect:"XPlat Code Coverage"

# Run specific test method
dotnet test --filter "FullyQualifiedName~MyTestMethod"

# Run tests by category
dotnet test --filter "Category=Integration"

Test Filtering

# Filter by test name
dotnet test --filter "Name~CalculatorTests"

# Filter by class
dotnet test --filter "ClassName=MyProject.Tests.CalculatorTests"

# Filter by priority
dotnet test --filter "Priority=1"

# Complex filters
dotnet test --filter "(Category=Unit|Category=Integration)&Priority=1"

Test Results and Coverage

# Generate test results in different formats
dotnet test --logger trx # Visual Studio format
dotnet test --logger junit # JUnit format
dotnet test --logger "console;verbosity=detailed"

# Generate code coverage report
dotnet test --collect:"XPlat Code Coverage" --results-directory ./TestResults

# Install and use ReportGenerator for HTML coverage reports
dotnet tool install -g dotnet-reportgenerator-globaltool
reportgenerator -reports:"./TestResults/*/coverage.cobertura.xml" -targetdir:"./coveragereport" -reporttypes:Html

Publishing and Deployment

Publishing Applications

# Publish for current platform
dotnet publish

# Publish for specific runtime
dotnet publish --runtime win-x64
dotnet publish --runtime linux-x64
dotnet publish --runtime osx-x64

# Self-contained deployment (includes .NET runtime)
dotnet publish --runtime win-x64 --self-contained true

# Framework-dependent deployment (requires .NET installed)
dotnet publish --runtime win-x64 --self-contained false

# Single file deployment
dotnet publish --runtime win-x64 --self-contained true --output ./publish /p:PublishSingleFile=true

# Trimmed deployment (removes unused code)
dotnet publish --runtime win-x64 --self-contained true /p:PublishTrimmed=true

Publishing Options

# Publish with specific configuration
dotnet publish --configuration Release

# Publish to specific output directory
dotnet publish --output ./dist

# Publish with version information
dotnet publish /p:Version=1.2.3 /p:AssemblyVersion=1.2.3.0

# Publish ReadyToRun (faster startup)
dotnet publish --runtime win-x64 --self-contained true /p:PublishReadyToRun=true

Tool Management

Global Tools

# Install global tool
dotnet tool install -g dotnet-ef # Entity Framework tools
dotnet tool install -g dotnet-aspnet-codegenerator # ASP.NET scaffolding
dotnet tool install -g dotnet-dump # Memory dump collection

# List installed tools
dotnet tool list -g

# Update tool
dotnet tool update -g dotnet-ef

# Uninstall tool
dotnet tool uninstall -g dotnet-ef

Local Tools

# Create tool manifest
dotnet new tool-manifest

# Install local tool
dotnet tool install dotnet-ef
dotnet tool install dotnet-format

# Run local tool
dotnet tool run dotnet-ef
dotnet ef migrations add InitialCreate

# List local tools
dotnet tool list

# Restore tools from manifest
dotnet tool restore

Project Information and Diagnostics

Project Information

# Show SDK information
dotnet --info

# List installed SDKs
dotnet --list-sdks

# List installed runtimes
dotnet --list-runtimes

# Show project dependencies
dotnet list package --include-transitive

# Show project references
dotnet list reference

Performance and Diagnostics

# Install diagnostic tools
dotnet tool install -g dotnet-counters
dotnet tool install -g dotnet-dump
dotnet tool install -g dotnet-trace

# Monitor performance counters
dotnet-counters monitor --process-id 1234

# Collect memory dump
dotnet-dump collect --process-id 1234

# Collect performance trace
dotnet-trace collect --process-id 1234

Advanced CLI Usage

Custom Project Templates

# Install custom template
dotnet new install MyCompany.Templates

# Create project from custom template
dotnet new mycompanyapi -n MyNewApi

# Uninstall template
dotnet new uninstall MyCompany.Templates

Environment and Configuration

# Run with environment variables
ASPNETCORE_ENVIRONMENT=Production dotnet run

# Set configuration values
dotnet run --ConnectionStrings:DefaultConnection="Server=prod;Database=MyDb"

# Use user secrets (development only)
dotnet user-secrets init
dotnet user-secrets set "ApiKey" "my-secret-key"
dotnet user-secrets list

Scripting and Automation

Create scripts for common workflows:

build.sh
#!/bin/bash

echo "Starting build process..."

# Restore packages
dotnet restore
if [ $? -ne 0 ]; then
echo "Package restore failed"
exit 1
fi

# Build solution
dotnet build --configuration Release --no-restore
if [ $? -ne 0 ]; then
echo "Build failed"
exit 1
fi

# Run tests
dotnet test --configuration Release --no-build --verbosity normal
if [ $? -ne 0 ]; then
echo "Tests failed"
exit 1
fi

# Publish application
dotnet publish --configuration Release --no-build --output ./dist
if [ $? -ne 0 ]; then
echo "Publish failed"
exit 1
fi

echo "Build completed successfully!"
build.ps1
# PowerShell version
Write-Host "Starting build process..." -ForegroundColor Green

try {
# Restore packages
dotnet restore
if ($LASTEXITCODE -ne 0) { throw "Package restore failed" }

# Build solution
dotnet build --configuration Release --no-restore
if ($LASTEXITCODE -ne 0) { throw "Build failed" }

# Run tests
dotnet test --configuration Release --no-build --verbosity normal
if ($LASTEXITCODE -ne 0) { throw "Tests failed" }

# Publish application
dotnet publish --configuration Release --no-build --output ./dist
if ($LASTEXITCODE -ne 0) { throw "Publish failed" }

Write-Host "Build completed successfully!" -ForegroundColor Green
}
catch {
Write-Host "Build failed: $_" -ForegroundColor Red
exit 1
}

CI/CD Integration

GitHub Actions Example

.github/workflows/dotnet.yml
name: .NET CI/CD

on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]

jobs:
test:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3

- name: Setup .NET
uses: actions/setup-dotnet@v3
with:
dotnet-version: 8.0.x

- name: Restore dependencies
run: dotnet restore

- name: Build
run: dotnet build --no-restore

- name: Test
run: dotnet test --no-build --verbosity normal --collect:"XPlat Code Coverage"

- name: Upload coverage reports
uses: codecov/codecov-action@v3
with:
file: ./coverage.xml

deploy:
needs: test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'

steps:
- uses: actions/checkout@v3

- name: Setup .NET
uses: actions/setup-dotnet@v3
with:
dotnet-version: 8.0.x

- name: Publish
run: dotnet publish --configuration Release --output ./publish

- name: Deploy to Azure
uses: azure/webapps-deploy@v2
with:
app-name: 'my-web-app'
publish-profile: ${{ secrets.AZURE_WEBAPP_PUBLISH_PROFILE }}
package: ./publish

Common Workflows

New Project Setup

# Create new solution with API and tests
mkdir MyProject
cd MyProject

# Create solution
dotnet new sln -n MyProject

# Create projects
dotnet new webapi -n MyProject.Api -o src/MyProject.Api
dotnet new classlib -n MyProject.Core -o src/MyProject.Core
dotnet new xunit -n MyProject.Tests -o tests/MyProject.Tests

# Add to solution
dotnet sln add src/MyProject.Api/MyProject.Api.csproj
dotnet sln add src/MyProject.Core/MyProject.Core.csproj
dotnet sln add tests/MyProject.Tests/MyProject.Tests.csproj

# Add project references
cd src/MyProject.Api
dotnet add reference ../MyProject.Core/MyProject.Core.csproj

cd ../../tests/MyProject.Tests
dotnet add reference ../../src/MyProject.Core/MyProject.Core.csproj
dotnet add reference ../../src/MyProject.Api/MyProject.Api.csproj

# Go back to solution root
cd ../..

# Build and test
dotnet build
dotnet test

Development Workflow

# Start development
dotnet watch run --project src/MyProject.Api

# In another terminal, run tests continuously
dotnet watch test

# Add new package
dotnet add src/MyProject.Api package Serilog.AspNetCore

# Create and apply EF migration
dotnet ef migrations add AddUserTable --project src/MyProject.Api
dotnet ef database update --project src/MyProject.Api

Troubleshooting Common Issues

Build Issues

# Clear NuGet cache
dotnet nuget locals all --clear

# Restore with no cache
dotnet restore --no-cache

# Clean build artifacts
dotnet clean
dotnet build

# Verbose output for debugging
dotnet build --verbosity diagnostic

Package Issues

# Check for package vulnerabilities
dotnet list package --vulnerable

# Update all packages to latest versions
dotnet list package --outdated
# Then manually update each package

# Force package reinstall
dotnet remove package PackageName
dotnet add package PackageName

Performance Tips

Build Performance

# Parallel builds
dotnet build --maxcpucount

# Skip restore if packages are already restored
dotnet build --no-restore

# Use binary log for analysis
dotnet build -bl:build.binlog

# Analyze with MSBuild Structured Log Viewer
dotnet tool install -g MSBuildStructuredLog
MSBuildStructuredLogViewer build.binlog

Development Performance

# Use file watching for continuous builds
dotnet watch build

# Skip tests during development builds
dotnet build --no-dependencies

# Use incremental builds
# MSBuild automatically handles incremental builds

Summary

The .NET CLI is an essential tool for .NET developers that provides:

Key Command Categories

  1. Project Management: new, sln, add, remove
  2. Build System: build, run, restore, clean
  3. Package Management: add package, remove package, list package
  4. Testing: test with various filters and options
  5. Publishing: publish with deployment options
  6. Tools: Global and local tool management

Best Practices

  • Use Solutions: Organize related projects in solutions
  • Automate Workflows: Create scripts for common tasks
  • Version Lock: Use specific package versions in production
  • CI/CD Integration: Incorporate CLI commands in pipelines
  • Monitor Performance: Use diagnostic tools for optimization

Essential Commands to Remember

# Project lifecycle
dotnet new webapi -n MyApi
dotnet build
dotnet run
dotnet test
dotnet publish

# Package management
dotnet add package PackageName
dotnet list package --outdated

# Solution management
dotnet sln add Project.csproj
dotnet add reference ../Other.csproj

Next Steps

Now that you've mastered the .NET CLI, learn about package management in detail:

Continue to Tutorial 6: What is NuGet? to understand the .NET package ecosystem and how to leverage third-party libraries effectively.


Need help with .NET development workflows? PBX Digital provides expert .NET consulting and development services. Contact us at mp@pbxdigital.net to optimize your development process.