Antoine Rodriguez Antoine Rodriguez - 1 month ago 11
C# Question

How can I get the real OS version in c#?

Since .NET 4 and Windows 8 or greater platforms it's quite uncertain to get the OS version where your program is ran.

For instance, running in a Windows 10, if my project has a Windows 8 DLL then the

Environement.OSVersion.Version
returns
6.2.9200.0
which is Windows 8 and not Windows 10.

This behaviour is explained in this question (crono's answer): Windows version in c#

So my question is the following: How can we detect for sure (and staying in a .NET way in order to be able to use it on non-Windows platforms) the OS version where our application is running?

Answer

If using other platforms than windows is not a concern, you can use Win32_OperatingSystem WMI class.

Win32_OperatingSystem represents a Windows-based operating system installed on a computer

//using System.Linq;
//using System.Management;
var query = "SELECT * FROM Win32_OperatingSystem";
var searcher = new ManagementObjectSearcher(query);
var info = searcher.Get().Cast<ManagementObject>().FirstOrDefault();
var caption = info.Properties["Caption"].Value.ToString();
var version = info.Properties["Version"].Value.ToString();
var spMajorVersion = info.Properties["ServicePackMajorVersion"].Value.ToString();
var spMinorVersion = info.Properties["ServicePackMinorVersion"].Value.ToString();

Remember to add a reference to System.Management.dll.

Note:

  • If you want to use Windows API Functions for this purpose, pay attention that GetVersionEx may be altered or unavailable for releases after Windows 8.1. Instead, use the Version Helper functions.
  • Starting with Windows 8, the Environment.OSVersion property returns the same major and minor version numbers for all Windows platforms. Therefore, we do not recommend that you retrieve the value of this property to determine the operating system version.
  • You may want to take a look at Mono FAQ - How to detect the execution platform?