Specify Targeted .NET Version for dotnet new Command and then dotnet Command Version

It is quite common for our development machine to install multiple versions of .NET SDK. By default, if we run dotnet new command from .NET CLI to create a new project, it will be creating a .NET project targeted to latest version regardless is it in preview or release candidate (RC). In order to specify the targeted .NET version, we can use the -f net7.0 option. The help message is like below:

$ dotnet new webapi --help

ASP.NET Core Web API (C#)
Author: Microsoft
Description: A project template for creating a RESTful Web API using ASP.NET Core controllers or minimal APIs, with optional support for OpenAPI and authentication.
# Omitting
  -f, --framework <net6.0|net7.0|net8.0|netcoreapp3.1>  The target framework for the project.
                                                        Type: choice
                                                          net8.0         Target net8.0
                                                          net7.0         Target net7.0
                                                          net6.0         Target net6.0
                                                          netcoreapp3.1  Target netcoreapp3.1
# Omitting

For example, the command below will create a new webapi project targeted .NET 7.0.

dotnet new webapi -o net7.0

Besides that, if you want your .NET CLI command to default to the version you want to use, you need to specify it too. The -f just for specify the targeted .NET project version. To do so, first you need to figure .NET version installed on your machine:

$ dotnet --list-sdks
3.1.416 [/home/ubuntu/dotnet/sdk]
6.0.400 [/home/ubuntu/dotnet/sdk]
7.0.202 [/home/ubuntu/dotnet/sdk]
8.0.100-rc.1.23455.8 [/home/ubuntu/dotnet/sdk]

If you want to use 7.0.202 for the dotnet command on the project folder, you can run the command below:

$  dotnet new globaljson --sdk-version 7.0.202
The template "global.json file" was created successfully.

The command above will create a global.json file inside the project folder. All directories including sub-directory will default to the version you specify.

{
  "sdk": {
    "version": "7.0.202"
  }
}

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.