Search code examples
c#.netvisual-studiotarget.net-standard

How to use conditional symbols when targeting multiple frameworks correctly (VS2017)


I want to migrate a library project which targeted .NET Framework 4.6.1 to a new one targeting both, .NET Framework 4.6.1 and .NET Standard 2.0.

<PropertyGroup Condition=" '$(OS)' == 'Windows_NT' "> 
    <TargetFrameworks>netstandard2.0;net461</TargetFrameworks>
</PropertyGroup>

In my current code I use, for example: System.Web.Hosting.HostingEnvironment.MapPath() method; so, I already added a condition in my .csproj file:

<ItemGroup Condition=" '$(TargetFramework)' == 'net461' ">
    <Reference Include="System.Web" />
</ItemGroup>

Now in my code, I know that I could have something like this:

#if NET461
   if (someFolderVar.StartsWith("~/"))
       someFolderVar = System.Web.Hosting.HostingEnvironment.MapPath(someFolderVar);
#endif

My question:

If later I change my project to target .NET Framework 4.7, will the above code be executed or it will be strictly targeted for .NET Framework 4.6.1 only? What condition to use for 4.6.1 and up?


Solution

  • Looks like I found a solution in this very good article. The use of NETFULL conditional symbol (from the article, but any name will do) should be a solution:

    <PropertyGroup Condition=" '$(TargetFramework)' == 'net461'">
      <DefineConstants>NETFULL</DefineConstants>
    </PropertyGroup>
    <PropertyGroup Condition=" '$(TargetFramework)' == 'net47'">
      <DefineConstants>NETFULL</DefineConstants>
    </PropertyGroup>
    

    and then the code:

    #if NETFULL
    if (someFolderVar.StartsWith("~/"))
       someFolderVar = System.Web.Hosting.HostingEnvironment.MapPath(someFolderVar);
    #endif