Home > Net >  Is it possible to set the TargetFramework on the commandline with dotnet build / restore?
Is it possible to set the TargetFramework on the commandline with dotnet build / restore?

Time:10-19

I want to remove the TargetFramework specifier from my project files and pass it via the commandline. Sounds easy:

dotnet build -f net5

But the big problem is the Nuget aspect. Because

dotnet restore

complains about the missing framework:

dotnet restore common\common.csproj Determining projects to restore... C:\Program Files\dotnet\sdk\5.0.400\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.TargetFrameworkInference.targets(92,5): error NETSDK1013: The TargetFramework value '' was not recognized. It may be misspelled. If not, then the TargetFrameworkIdentifier and/or TargetFrameworkVersion properties must be specified explicitly.

The problem is that dotnet restore does not accept a TargetFamework argument. So I am forced to write the TargetFramework into the conig file: Even worse, there is always a single Nuget restoration in the obj directories, so upon every switch between target frameworks I need to modify the config file and do a fresh restore. This is extremely cumbersome and I wonder how this can be avoided.

If this cannot be solved I would kick out NuGet and reference the package assemblies directly.

Thanks for any help

CodePudding user response:

Since dotnet restore and dotnet build are wrappers around dotnet msbuild, you can use all MSBuild switches to change behavior of build system.

Here we need to set target framework, which can be done by

  • setting property in project file: <TargetFramework>net5.0</TargetFramework>

OR

  • setting property through command line docs: dotnet restore -p:TargetFramework=net5.0

OR

  • setting environment variable which is not recommended (by me)
  • Related