.net.net-coremsbuild

C# - Choose TargetFrameworks based on CPU Platform


I have a legacy C# application compiled for x86. I am upgrading it to VS 2022 and enabling x64 in addition to x86. I would like to compile the legacy x86 using .Net framework 4.5 and x64 using .Net 8.0. So, the valid combinations are x86-.NetFramework4.5 and x64-.Net6.0.

Is it possible to have TargetFrameworks set based on the CPU platform?


Solution

  • You can't directly set TargetFramework based on the CPU platform in a single project file.
    However, you can achieve this by using multiple configurations in your project.

    Create separate configurations for x86 and x64 in your .csproj file and specify the corresponding TargetFramework for each configuration.

    For example:

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <RootNamespace>YourNamespace</RootNamespace>
        <AssemblyName>YourAssemblyName</AssemblyName>
        <TargetFrameworks>net45;net8.0</TargetFrameworks>
      </PropertyGroup>
    
      <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x86'">
        <TargetFramework>net45</TargetFramework>
        <PlatformTarget>x86</PlatformTarget>
      </PropertyGroup>
    
      <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x86'">
        <TargetFramework>net45</TargetFramework>
        <PlatformTarget>x86</PlatformTarget>
      </PropertyGroup>
    
      <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
        <TargetFramework>net8.0</TargetFramework>
        <PlatformTarget>x64</PlatformTarget>
      </PropertyGroup>
    
      <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
        <TargetFramework>net8.0</TargetFramework>
        <PlatformTarget>x64</PlatformTarget>
      </PropertyGroup>
    
    </Project>