萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

C# 判斷作業系統版本:從 Windows 95 到 Windows 11

前言

透過 `Environment.OSVersion` 取得版本號,對照 Major/Minor/Build 判斷作業系統。注意:Windows 8.1/10/11 在未宣告相容性清單時會回報 6.2 (Windows 8),需在 `app.manifest` 加入 `` 區段才能取得真實版本。

基本判斷邏輯 (適用已宣告相容性的應用程式)

public static string GetOSDisplayName()
{
    var os = Environment.OSVersion;
    var v = os.Version;
    
    if (os.Platform != PlatformID.Win32NT) return "非 NT 核心系統";

    return (v.Major, v.Minor, v.Build) switch
    {
        (3, 51, _) => "Windows NT 3.51",
        (4, 0, _) => "Windows NT 4.0",
        (5, 0, _) => "Windows 2000",
        (5, 1, _) => "Windows XP",
        (5, 2, _) => "Windows Server 2003 / XP x64",
        (6, 0, _) => "Windows Vista / Server 2008",
        (6, 1, _) => "Windows 7 / Server 2008 R2",
        (6, 2, _) => "Windows 8 / Server 2012",
        (6, 3, _) => "Windows 8.1 / Server 2012 R2",
        (10, 0, _) when v.Build < 22000 => "Windows 10",
        (10, 0, _) => "Windows 11 / Server 2022",
        _ => $"Windows {v.Major}.{v.Minor} (Build {v.Build})"
    };
}

關鍵:應用程式資訊清單宣告相容性

在 `app.manifest` 的 `` 內加入:

<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
  <application>
    <!-- Windows 10 -->
    <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
    <!-- Windows 8.1 -->
    <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />
    <!-- Windows 8 -->
    <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />
    <!-- Windows 7 -->
    <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />
    <!-- Windows Vista -->
    <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />
  </application>
</compatibility>

**未加入此區段時**,Windows 8.1 以上皆回報 `6.2.9200` (Windows 8),導致版本判斷失誤。

替代方案:WMI / Registry (不需 Manifest)

// WMI 查詢 (較慢但準確)
public static string GetOSFromWMI()
{
    using (var searcher = new System.Management.ManagementObjectSearcher("SELECT Caption, Version FROM Win32_OperatingSystem"))
    foreach (var obj in searcher.Get())
        return $"{obj["Caption"]} {obj["Version"]}";
    return "Unknown";
}

// 登錄表 (快速)
public static string GetOSFromRegistry()
{
    using (var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
    {
        string name = key.GetValue("ProductName")?.ToString();
        string build = key.GetValue("CurrentBuildNumber")?.ToString();
        return $"{name} (Build {build})";
    }
}

.NET 5/6/7/8 專用 API


// .NET 5+ 可直接用
OperatingSystem.IsWindows()           // 是否 Windows
OperatingSystem.IsWindowsVersionAtLeast(10, 0, 22000) // 是否 >= Win11
Environment.OSVersion.Version         // 仍受 Manifest 影響

建議新專案直接使用 `OperatingSystem.IsWindowsVersionAtLeast` 進行版本檢查,無需自行解析版本號。

copyright © 萬盛學電腦網 all rights reserved