如何在C#中获得真实的OS版本? [英] How can I get the real OS version in c#?

查看:68
本文介绍了如何在C#中获得真实的OS版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于.NET 4和Windows 8或更高版本的平台,因此很难确定要在其中运行程序的OS版本.

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

例如,在Windows 10中运行,如果我的项目具有Windows 8 DLL,则 Environment.OSVersion.Version 返回 6.2.9200.0 ,即Windows 8和不是Windows 10.

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.

此问题对此问题进行了解释( crono 的答案):Windows版本为c#

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

所以我的问题是:我们如何确定正在运行应用程序的OS版本(并以.NET方式运行,以便能够在非Windows平台上使用它?)?

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?

链接到MSDN:

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

推荐答案

如果不考虑使用Windows以外的其他平台,则可以使用

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

Win32_OperatingSystem 表示一个基于Windows的操作系统安装在计算机上

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();

记住要添加对 System.Management.dll 的引用.

注意:

  • 如果要为此目的使用Windows API函数,请注意 Environment.OSVersion 属性为所有Windows平台返回相同的主要和次要版本号.因此,我们不建议您检索此属性的值来确定操作系统版本.
  • 您可能想看看 查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆