PROWAREtech

articles » current » dot-net » operating-system-detection

.NET: Operating System Detection

How to detect if the operating system is Linux, MacOS or Windows using C#.

It is easy to check the operating system that the app is running on in .NET and .NET Core. Use the RuntimeInformation class that is part of the System.Runtime.InteropServices namespace.

By knowing the OS, the app can load appropriate libraries or execute appropriate executables/scripts.

using System.Runtime.InteropServices;

public class OSCheck
{
	public static bool IsLinux() => RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
	public static bool IsOSX() => RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
	public static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
}

Here is the complete example:

using System;

namespace ConsoleApp1
{
	public class OSCheck
	{
		public static bool IsLinux() => System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Linux);
		public static bool IsOSX() => System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.OSX);
		public static bool IsWindows() => System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows);
	}

	class Program
	{
		static void Main(string[] args)
		{
			if (OSCheck.IsLinux())
				Console.WriteLine("Linux");
			if (OSCheck.IsOSX())
				Console.WriteLine("OSX");
			if (OSCheck.IsWindows())
				Console.WriteLine("Windows");
		}
	}
}

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE