Search code examples
c#windowsversion

C# determine OS is Windows 7 or WIndows Windows Server 2008


I am using .NET framework 3.5 version, and the program has to detect all the Windows versions(including Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows Server 2008, Windows Server 2008 R2, Windows Server 2012).

The problem is how can I determine the OS in below situations?

  • Windows Vista and Windows Server 2008 Version number both are 6.0.
  • Windows 7 and Windows Server 2008 R2 Version number both are 6.1.
  • Windows 8 and Windows Server 2012 Version number both are 6.2.

I have found the below code but I can't use because I'm using .NET Framework 3.5.

var name = (from x in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem").Get().OfType<ManagementObject>()
                  select x.GetPropertyValue("Caption")).FirstOrDefault();
return name != null ? name.ToString() : "Unknown";

How can I solve this problem?


Solution

  • I'm assuming the problem with that code is that it uses LINQ. You can still use WMI to check it, just don't use LINQ. I also think it's better to check the ProductType rather than Caption.

    using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem"))
    {
        foreach (ManagementObject managementObject in searcher.Get())
        {
            uint productType = (uint)managementObject.GetPropertyValue("ProductType");
            // productType will be 1 for workstation, 2 for domain controller,
            // 3 for normal server
        }
    }
    

    Then just check version number to determine actual OS version.

    Another way is to use registry and check the key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ProductOptions\ProductType. This will have values WinNT, ServerNT or LanmanNT to mark the same options as the WMI code.