首先通过微软官方文档:https://learn.microsoft.com/zh-cn/windows/win32/sysinfo/operating-system-version了解各个操作系统对应的版本号
下面介绍3种获取版本号的方式及弊端
1. Environment.OSVersion.Version
OperatingSystem os = Environment.OSVersion;// 判断操作系统版本if (os.Version.Major == 10 && os.Version.Build < 22000){textBlock.Text = "当前操作系统是 Windows 10";}else if (os.Version.Major == 10 && os.Version.Build >= 22000){textBlock.Text = "当前操作系统是 Windows 11";}else{textBlock.Text = $"当前操作系统既不是 Windows 10也不是 Windows 11";}
该方式适合.NET Framework,并且必须添加应用程序清单文件,并且需要把程序应用程序清单文件里面的supportedOS项取消注释(默认是注释的)
2. System.Runtime.InteropServices.RuntimeInformation.OSDescription
var osDescription = System.Runtime.InteropServices.RuntimeInformation.OSDescription;var osDescs = osDescription.Split(' ');foreach (var osDesc in osDescs){if (!osDesc.Contains(".")) continue;var versions = osDesc.Split('.');if (versions.Length < 2) continue;if (int.Parse(versions[0]) == 10 && int.Parse(versions[2]) < 22000){textBlock.Text = "当前操作系统是 Windows 10";}else if (int.Parse(versions[0]) == 10 && int.Parse(versions[2]) >= 22000){textBlock.Text = "当前操作系统是 Windows 11";}else{textBlock.Text = $"当前操作系统既不是 Windows 10也不是 Windows 11";}}
该方式适合.NET Core以上(.net framework 4.7以上)
3. 从注册表中获取版本信息
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion")){string productName = key.GetValue("ProductName") as string;int majorVersion = (int)key.GetValue("CurrentMajorVersionNumber");var buildNumber = int.Parse(key.GetValue("CurrentBuildNumber").ToString());if (!string.IsNullOrEmpty(productName) && productName.ToLower().Contains("windows")){if (majorVersion > 10 || majorVersion == 10 && buildNumber >= 22000){textBlock.Text = "当前操作系统是 Windows 11";}else if (majorVersion == 10 && buildNumber < 22000){textBlock.Text = "当前操作系统是 Windows 10";}else{textBlock.Text = $"当前操作系统既不是 Windows 10也不是 Windows 11";}}}
该方式暂时没发现问题,但是需要使用版本号推断是Win11
4. 从WMI获取系统版本(推荐)
foreach (var o in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem").Get()){var obj = (ManagementObject)o;// Microsoft Windows 11 企业版var caption = obj.GetPropertyValue("Caption");// 10.0.22000var version = obj.GetPropertyValue("Version");break;}
该方式可以准确获取Windows版本描述和版本号