.netvisual-studiomsbuildcsprojtarget-framework

How to change targetframework based on Visual Studio version


I would like to support from .NET Standard 2.0 to .NET 8.0 every target in a projects. Currently

<TargetFrameworks>$(ExtraTargetFrameworks)netstandard2.0</TargetFrameworks>

is used along with

<Project>
    <PropertyGroup>
        <ExtraTargetFrameworks></ExtraTargetFrameworks>
    </PropertyGroup>
    <PropertyGroup Condition="'$(UseDotnet6SDK)'=='True'">
        <ExtraTargetFrameworks>net6.0;</ExtraTargetFrameworks>
    </PropertyGroup>
</Project>

I would just add net8.0 to the TargetFrameworks, but that's a bit problematic for the following reasons:

So the question is: how to include net8.0 in TargetFrameworks if using Visual Studio 2022 or later or not using Visual Studio at all, but not when using an older version of Visual Studio?

I was thinking of adding conditions to the property groups, like so:

<PropertyGroup Condition="'$(Flavor)'=='DEBUG'">

based on this

I have found a list of reserved properties, that I assume could be used in conditions here, but this does not list a way of querying the Visual Studio version - although some paths listed usually contain the version. Would it be possible to regex magic that for the condition?

I don't want to specify properties on the command line, all should be in the .csproj or in other build/project files.


Solution

  • If you want to change targetframework based on visual studio version, you can use property VisualStudioVersion. For more information, please check the Common MSBuild project properties

    For example

    <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
    <Target Name="PrintVisualStudioInfo">
        <Message Text="VisualStudioVersion: '$(VisualStudioVersion)'" />
    </Target>
    

    enter image description here

    <Project>
        <PropertyGroup>
            <ExtraTargetFrameworks></ExtraTargetFrameworks>
        </PropertyGroup>
        <PropertyGroup Condition="'$(VisualStudioVersion)'=='17.0'">
            <ExtraTargetFrameworks>net8.0;</ExtraTargetFrameworks>
        </PropertyGroup>
    </Project>
    

    Hope it can help you.