从Windows 2000开始,Windows Kernel 库ntdll.dll 中的RtlGetVersion函数可以获取操作系统版本详细信息。在Window 10 20H2中,这个函数依然有效
using System;
using System.Runtime.InteropServices;
using System.Security;
namespace ConsoleApp2
{
class Program
{
[SecurityCritical]
[DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern int RtlGetVersion(ref OSVERSIONINFOEX versionInfo);
[StructLayout(LayoutKind.Sequential)]
internal struct OSVERSIONINFOEX
{
// The OSVersionInfoSize field must be set to Marshal.SizeOf(typeof(OSVERSIONINFOEX))
internal int OSVersionInfoSize;
internal int MajorVersion;
internal int MinorVersion;
internal int BuildNumber;
internal int PlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
internal string CSDVersion;
internal ushort ServicePackMajor;
internal ushort ServicePackMinor;
internal short SuiteMask;
internal byte ProductType;
internal byte Reserved;
}
static void Main(string[] args)
{
var osVersionInfo = new OSVERSIONINFOEX { OSVersionInfoSize = Marshal.SizeOf(typeof(OSVERSIONINFOEX)) };
if (RtlGetVersion(ref osVersionInfo) != 0)
{
// 错误处理
Console.WriteLine("RtlGetVersion Error!");
}
else
Console.WriteLine($"Windows Version {osVersionInfo.MajorVersion}.{osVersionInfo.MinorVersion}.{osVersionInfo.BuildNumber}");
Console.ReadKey();
}
}
}