1. 程式人生 > 其它 >【C# .Net Framework】如何正確檢測Windows版本資訊

【C# .Net Framework】如何正確檢測Windows版本資訊

技術標籤:程式設計經驗c#

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