Detecting the Operating System in .NET Core

Sometimes, it might be necessary to detect on which operating system a .NET Core application is currently running. The various operating system platforms are described by the OSPlatform struct which defines three static properties:

  • OSPlatform.Windows
  • OSPlatform.OSX
  • OSPlatform.Linux

Using the RuntimeInformation class found in the System.Runtime.InteropServices namespace, we can check for a specific operating system:

if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
    Console.WriteLine("We're on macOS!");
}

The above code works and reads just fine, but we can go one step further and write a little helper class with three static methods for detecting Windows, macOS, and Linux:

using System.Runtime.InteropServices;

public static class OperatingSystem
{
    public static bool IsWindows() =>
        RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

    public static bool IsMacOS() =>
        RuntimeInformation.IsOSPlatform(OSPlatform.OSX);

    public static bool IsLinux() =>
        RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
}

This way, we can improve the readability of our platform check and make the code even terser at the same time. Now, it almost reads like a proper English sentence:

if (OperatingSystem.IsMacOS())
{
    Console.WriteLine("We're on macOS!");
}

Use the coupon code LAUNCHDAY for $10 off!

Learn React

Comments