.netmsbuildnuget

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


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 config 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.


Solution

  • 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

    OR

    OR