在后台,Environment.OSVersion 使用已被弃用的 GetVersionEx function。该文档警告您观察到的行为:
未针对 Windows 8.1 或 Windows 10 显示的应用程序将返回 Windows 8 操作系统版本值 (6.2)。
文档继续推荐:
识别当前操作系统通常不是确定特定操作系统功能是否存在的最佳方式。这是因为操作系统可能在可再发行的 DLL 中添加了新功能。与其使用 GetVersionEx 来确定操作系统平台或版本号,不如测试该功能本身是否存在。
如果上述建议不适合您的情况,并且您确实想检查实际运行的操作系统版本,那么文档还提供了关于此的提示:
要将当前系统版本与所需版本进行比较,请使用 VerifyVersionInfo 函数而不是使用 GetVersionEx 自行进行比较。
以下文章发布了使用 VerifyVersionInfo 函数的有效解决方案:Version Helper API for .NET。
充分感谢那篇文章的作者,以下代码 sn-p 应该提供您正在寻找的行为:
public class Program
{
static void Main(string[] args)
{
Console.WriteLine(IsWindowsVersionOrGreater(6, 3, 0)); // Plug in appropriate values.
}
[StructLayout(LayoutKind.Sequential)]
struct OsVersionInfoEx
{
public uint OSVersionInfoSize;
public uint MajorVersion;
public uint MinorVersion;
public uint BuildNumber;
public uint PlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string CSDVersion;
public ushort ServicePackMajor;
public ushort ServicePackMinor;
public ushort SuiteMask;
public byte ProductType;
public byte Reserved;
}
[DllImport("kernel32.dll")]
static extern ulong VerSetConditionMask(ulong dwlConditionMask,
uint dwTypeBitMask, byte dwConditionMask);
[DllImport("kernel32.dll")]
static extern bool VerifyVersionInfo(
[In] ref OsVersionInfoEx lpVersionInfo,
uint dwTypeMask, ulong dwlConditionMask);
static bool IsWindowsVersionOrGreater(
uint majorVersion, uint minorVersion, ushort servicePackMajor)
{
OsVersionInfoEx osvi = new OsVersionInfoEx();
osvi.OSVersionInfoSize = (uint)Marshal.SizeOf(osvi);
osvi.MajorVersion = majorVersion;
osvi.MinorVersion = minorVersion;
osvi.ServicePackMajor = servicePackMajor;
// These constants initialized with corresponding definitions in
// winnt.h (part of Windows SDK)
const uint VER_MINORVERSION = 0x0000001;
const uint VER_MAJORVERSION = 0x0000002;
const uint VER_SERVICEPACKMAJOR = 0x0000020;
const byte VER_GREATER_EQUAL = 3;
ulong versionOrGreaterMask = VerSetConditionMask(
VerSetConditionMask(
VerSetConditionMask(
0, VER_MAJORVERSION, VER_GREATER_EQUAL),
VER_MINORVERSION, VER_GREATER_EQUAL),
VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
uint versionOrGreaterTypeMask = VER_MAJORVERSION |
VER_MINORVERSION | VER_SERVICEPACKMAJOR;
return VerifyVersionInfo(ref osvi, versionOrGreaterTypeMask,
versionOrGreaterMask);
}
}
免责声明:我还没有 Windows 10,所以我没有在 Windows 10 上测试过代码。