Dotnet Core: How to Detect Operating System OS platform [.Net Core]

satinder singh / Updated : / 0 Comments

Determining OS platform in .NET Core: Here in this article will learn how to get the operating system details on which our .NET Core application is running.Theirs a requirement in my one application where I have to detect on which operating system my .NET Core application is running, .i.e Windows Operating System, OSX Operating System, Linux Operating System and based on OS platform have to do further logic.
By using Environment.OSVersion we can achieve same in  .Net Framework. But in  .NET CORE Environment.OSVersion is not working so I was like how to determine whether my .NET Core app is running on Mac or Windows?

Finally, with a little Google, I came to know about InteropServices.RuntimeInformation. Runtime.InteropServices: Provides APIs to query about runtime and OS

OSPlatform defines three static properties

  1. OSPlatform.Windows
  2. OSPlatform.OSX
  3. OSPlatform.Linux

Code: To determine OS platform in DotNet Core.

#Code For Windows

var isWindows=System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
	 Console.WriteLine("Hello, this is windows");

#Similarly, we can check for Mac

var isOSX=System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
  Console.WriteLine("Hello, this is Mac OS");

# For Linux

var isLinux=System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
   Console.WriteLine("Hello, this is Linux");


Finally, with Runtime.InteropServices we able to detect Operating System in Dot.Net Core.

Further, we can generalize this method programmatically to use it in our project which tells us the current OS platform. So our final code looks like as written below.

using System.Runtime.InteropServices;

public static class myOperatingSystem
    public static bool isWindows() =>RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
    public static bool isMacOS() =>RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
    public static bool isLinux() =>RuntimeInformation.IsOSPlatform(OSPlatform.Linux);

And this way we use our generalize method to detect Operating System in Dot.Net Core

if (myOperatingSystem.IsMacOS())
    Console.WriteLine("Hello, this is Mac OS");


Other Reference: Determine operating system version

Post Comment

Your email address will not be published. Required fields are marked *