How to check the OS version at runtime, e.g. on Windows or Linux, without using a conditional compilation statement

I found this recommendation on one of Microsoft’s blogs:

We recommend you to use RuntimeInformation.IsOSPlatform() for platform
checks.

Reference: Announcing the Windows Compatibility Pack for .NET Core

IsOSPlatform() takes an argument of types OSPlatform which has three values by default: Windows, Linux and OSX. It can be used as follow:

if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
  // Do something
}

The API is part of .NET Standard 2.0, and therefore available in .NET Core 2.0 and .NET Framework 4.7.1.

Leave a Comment