Search code examples
c#linux.net-corecsprojconditional-compilation

How to define compile time constants based on platform (Linux vs Windows) in C# / .Net.Core?


Inspired by this blog, I tried to implement this like so:

<DefineConstants Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Windows)))' == 'true'">Windows</DefineConstants>
<DefineConstants Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Linux)))' == 'true'">POSIX</DefineConstants>

but I get this error:

The function "IsOSPlatform" on type "System.Runtime.InteropServices.RuntimeInformation" is not available for execution as an MSBuild property function

Is there a way to get around this problem? The project loads perfectly without those two DefineConstants lines.

MSBuild Error


Solution

  • This method only works on the 15.0 (or up) version of MSBuild. Since mono right now does not come with this version of MSBuild.

    There is an open issue on this here

    Visual studio can compile the code with this in the .csproj file.