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


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. There is a requirement in one of my applications where I have to detect the operating system. That is on which operating system my .NET Core application is running, .i.e Windows Operating System, OSX Operating System, or on Linux Operating System, and based on OS platform have to do further logic.

In .Net Framework by using Environment.OSVersion very easily we can detect the Operating System. 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 the Dot.Net Core application. 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:

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.

Post Comment

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