Creating and Managing .NET Core Projects
The .NET Core Command-Line Interface (CLI) is a powerful toolset for developing, building, testing, and publishing .NET applications. This tutorial will guide you through the essential commands for managing your .NET Core projects.
1. Creating a New Project
To start a new .NET Core project, use the dotnet new
command followed by the project template. Common templates include:
console
: A .NET Core console application.classlib
: A .NET Core class library.webapi
: A .NET Core web API project.webapp
: A .NET Core web application (Razor Pages).
Open your terminal or command prompt.
Navigate to the directory where you want to create your project.
cd path/to/your/projects
Create a new console application named 'MyConsoleApp':
dotnet new console -o MyConsoleApp
The -o
flag specifies the output directory for the new project.
dotnet new --list
.
2. Building a Project
The dotnet build
command compiles your project and its dependencies. It generates the necessary output files in the build output directory (usually bin/Debug
or bin/Release
).
Navigate into your project directory:
cd MyConsoleApp
Build the project:
dotnet build
dotnet build -c Release
.
3. Running a Project
The dotnet run
command builds and executes your project. It's a convenient way to test your application during development.
Ensure you are in your project directory.
Run the project:
dotnet run
4. Restoring Dependencies
Before building or running, you often need to restore the project's NuGet package dependencies. This is handled automatically by dotnet build
and dotnet run
, but you can also do it explicitly with dotnet restore
.
Restore dependencies for your project:
dotnet restore
5. Publishing a Project
When you're ready to deploy your application, you use dotnet publish
. This command compiles, restores, and packages your application into a deployable format.
Publish the project for a specific framework (e.g., .NET 6.0):
dotnet publish --framework net6.0
This creates a self-contained deployment or a framework-dependent deployment in the publish
folder.
dotnet publish --runtime win-x64
(replace win-x64
with your target runtime identifier).
6. Managing NuGet Packages
The CLI also allows you to manage NuGet packages for your projects.
Adding a Package
dotnet add package Newtonsoft.Json
Removing a Package
dotnet remove package Newtonsoft.Json
Listing Packages
dotnet list package
Conclusion
The .NET Core CLI is an indispensable tool for modern .NET development. By mastering these fundamental commands, you can efficiently create, build, run, and deploy your applications.
Explore further by checking out commands like dotnet test
for running unit tests and dotnet pack
for creating NuGet packages.
For more detailed information, refer to the official .NET CLI documentation.