Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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 Environment.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?

Link to MSDN:

https://msdn.microsoft.com/en-us/library/system.environment.osversion(v=vs.110).aspx

like image 248
Antoine Rodriguez Avatar asked Sep 05 '15 17:09

Antoine Rodriguez


People also ask

How do I find my C drive OS version?

Start it up. Under the tools menu, select >> load hive. It then shows all your drives, select the windows folder of the drive in question. It instantly provides the version and keys.

Where can I find the OS version?

Android DevicesGo to the home screen of your device. Touch "Settings," then touch "About Phone" or "About Device." From there, you can find the Android version of your device.

How do I find my OS build number?

In the Settings window, navigate to System > About. Scroll down a bit and you'll see the information you're after. Navigate to System > About and scroll down. You'll see the “Version” and “Build” numbers here.


1 Answers

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?
like image 112
Reza Aghaei Avatar answered Oct 12 '22 03:10

Reza Aghaei