Determine Current Operating System in .Net Core

By: Chris Dunn

What Operating System is my .net application running on?  Seems weird to ask that question doesn't it.  But with .net core we now have the opportunity to more easily deploy cross-platform solutions using .Net and C#. So previously the question of which OS platform we were running for our application didn't really concern many .net developers. Fortunately, we now have to consider such things. (I'm not forgetting mono).

Luckily .Net Core has us covered with OS information included with the Runtime Information. It's pretty straightforward but I've built a utility class to easily grab the information as true/false for each OS. You'll need to make sure you've included the System.Runtime.InteropServices reference.

using System.Runtime.InteropServices;


public static class CurrentOS
{
    public static bool IsOSWindows () => RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
    public static bool ISOSLinux() => RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
    public static bool IsOSOSX() => RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
}

When you need to determine the OS platform in your code, you just call the utility methods for each OS. You can then make any configuration adjustments and control logic based on the current operating system.

            
if (CurrentOS.ISOSLinux())
    Console.WriteLine("OS is Linux");
else if (CurrentOS.IsOSWindows())
    Console.WriteLine("OS is Windows");
else if (CurrentOS.ISOSLinux())
    Console.WriteLine("OS is OSX");
Console.ReadKey();

Knowing the OS you are running on, gives you the chance to customize your configuration. Perhaps the database used, file locations, logging output and a whole host of things I can't think of right now.

Tags: .net core c#

Copyright 2023 Cidean, LLC. All rights reserved.

Proudly running Umbraco 7. This site is responsive with the help of Foundation 5.