How to Use a Specific Version of the Dotnet Command
By default, dotnet runs the newest version that it finds on our machine. While most of the time that is not a problem, it looks a bit different when a new version of .Net is out. Then we may not yet be ready to upgrade and wish to use the older .Net version. But how can we do that?
global.json to the rescue
We can create a global.json file that specifies which version of the .Net SDK runs when we use dotnet. The biggest use case for this is the build process, but we can use it for everything that runs on the dotnet command.
First, let us check what SDKs we have on our machine:
dotnet --list-sdks
6.0.427 [C:\Program Files\dotnet\sdk]
7.0.410 [C:\Program Files\dotnet\sdk]
8.0.110 [C:\Program Files\dotnet\sdk]
8.0.403 [C:\Program Files\dotnet\sdk]
We can create a global.json file and specify the version of one of our SDKs:
This creates us a global.json file with this content:
We can check if everything works and if the dotnet command picks version 8.0.110:
Specify how it should handle newer versions
While this basic approach works, it means that everyone on the team must install the exact same SDK. This is not great, and we may want to have a bit more flexibility. Luckily for us, there is the rollForward option that can help us. From all the values it supports are these 3 the most important ones:
- latestMajor: It will use the highest major version (X.y.z) it could find and use the next version of .Net.
- latestMinor: It will use the highest minor number for the same major number (8.X.y)
- latestFeature: It will use the highest feature number (8.0.X)
We can set the rollForward option when we create the global.json file or add it in our existing file:
Our global.json has now the roll-forward option set to latestFeature:
If we check the version of dotnet now, it will use the newest feature version for our 8.0.110 version:
Conclusion
The global.json file is a great trick to use a specific version of the dotnet command. It will only work in the folder (and subfolders) where you put the global.json file, but that is often enough to get the results we need.