This post will discuss how to determine the operating system in C#.

1. Using RuntimeInformation Class

The recommended solution to identify the current platform is to use the RuntimeInformation.IsOSPlatform() method from System.Runtime.InteropServices namespace. It takes an argument of type OSPlatform Struct, which has four properties: Windows, Linux, OSX, and FreeBSD representing Windows, Linux, OSX, and FreeBSD operating systems respectively.

Download  Run Code

 
You can get more information about the current operating system using the RuntimeInformation.OSDescription property. For example,

Download  Run Code

Sample Output:

OSDescription: Microsoft Windows 10.0.22000
or
OSDescription: Unix 4.15.0.176

2. Using OperatingSystem Class

The OperatingSystem class contains several static utility methods and properties that provide information about the current runtime operating system. To determine whether the current application is running on Windows, Linux, macOS, or Android, you can use IsWindows(), IsLinux(), IsMacOS(), IsAndroid() methods respectively. For example,

Download  Run Code

 
You can get more information about the current operating system like operating system platform and version with the Environment.OSVersion property.

Download  Run Code

Sample Output:

Platform: Win32NT, Version: Microsoft Windows NT 10.0.22000.0
or
Platform: Unix, Version: Unix 4.15.0.176

3. Using Environment.OSVersion Property

In .NET 5 and later, you can get the current operating system name and version using the Environment.OSVersion property.

Download  Run Code

Sample Output:

Microsoft Windows NT 10.0.22000.0
or
Unix 4.15.0.176

 
Be careful while using this in .NET versions before .NET 5. If your application runs under Windows compatibility mode, Environment.OSVersion may result in an incorrect OS version.

That’s all about determining the operating system in C#.