DotNet Core and Standard are cross platform and sometimes we need to know what OS we are running on.
To check what operating system the application is currently running on, we can simply use the following method on RuntimeInformation:
RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
There are 3 OS’s to detect in the enum OSPlatform:
public enum OSPlatform{
Windows,
Linux,
OSX
}OSPlatform.Windows OSPlatform.Linux OSPlatform.OSX
An easy class to implement if you need to check the current OS would be something like the one below, that I always have handy, and you can just drop this in anywhere you see fit:
using System.Runtime.InteropServices;
public static class CurrentOperatingSystem
{
/// <summary>
/// Returns true id current OS is Windows
/// </summary>
public static bool IsWindows() => IsOSPlatform(OSPlatform.Windows);
/// <summary>
/// Returns true id current OS is Linux
/// </summary>
public static bool IsLinux() => IsOSPlatform(OSPlatform.Linux);
/// <summary>
/// Returns true id current OS is OSX
/// </summary>
public static bool IsMacOS() => IsOSPlatform(OSPlatform.OSX);
/// <summary>
/// Returns true id current OS matches OSPlatform
/// </summary>
/// <param name="os">OS Platform to check for</param>
public static bool IsOSPlatform(OSPlatform osPlatform) =>
RuntimeInformation.IsOSPlatform(osPlatform);
}And call it like this:
if (CurrentOperatingSystem.IsWindow())
Console.WriteLine("Yay it's Windows!")Or
if (CurrentOperatingSystem.IsOSPlatform(OSPlatform.Linux)
Console.WriteLine("Yay it's Linux!")Enjoy 😊
Hi, my name is Niels, I am a passionate software developer from Denmark with a love for coding and solving real-world problems! I taught myself C# back in 2012 in my spare time and I loved it! I went on and graduated from Computer Science in 2016 where I got hired by