在.NET中检测Windows版本

194

我该如何在.NET中检测Windows操作系统的版本?

我可以使用什么代码?

18个回答

349

System.Environment.OSVersion提供了区分大部分Windows操作系统主要版本所需的信息,但并非全部。它由三个组件组成,这些组件映射到以下Windows版本:

+------------------------------------------------------------------------------+
|                    |   PlatformID    |   Major version   |   Minor version   |
+------------------------------------------------------------------------------+
| Windows 95         |  Win32Windows   |         4         |          0        |
| Windows 98         |  Win32Windows   |         4         |         10        |
| Windows Me         |  Win32Windows   |         4         |         90        |
| Windows NT 4.0     |  Win32NT        |         4         |          0        |
| Windows 2000       |  Win32NT        |         5         |          0        |
| Windows XP         |  Win32NT        |         5         |          1        |
| Windows 2003       |  Win32NT        |         5         |          2        |
| Windows Vista      |  Win32NT        |         6         |          0        |
| Windows 2008       |  Win32NT        |         6         |          0        |
| Windows 7          |  Win32NT        |         6         |          1        |
| Windows 2008 R2    |  Win32NT        |         6         |          1        |
| Windows 8          |  Win32NT        |         6         |          2        |
| Windows 8.1        |  Win32NT        |         6         |          3        |
+------------------------------------------------------------------------------+
| Windows 10         |  Win32NT        |        10         |          0        |
+------------------------------------------------------------------------------+

如果您想获取更全面的关于当前执行环境运行的确切 Windows 版本的信息,可以使用 这个库

重要提示:如果您的可执行程序集清单没有明确说明您的可执行程序集与 Windows 8.1 和 Windows 10.0 兼容,则 System.Environment.OSVersion 将返回 Windows 8 版本(6.2),而不是 6.3 或 10.0!来源:这里

更新:在 .NET 5.0 及更高版本中,System.Environment.OSVersion 总是返回实际的操作系统版本。有关更多信息,请参见Environment.OSVersion 返回正确的操作系统版本


13
这张表至少部分是错误的,导致答案(原本关于Win7的)也是错误的。人们不加检查就点赞,而实际上它并没有起作用。在我的电脑上,Win7不具有次要版本号为2的情况。我使用的是Win7 SP1,我的版本信息显示为“Microsoft Windows NT 6.1.7601 Service Pack 1”。查看Environment.OSVersion显示Build=7601,Major=6,MajorRevision=1,Minor=1,MinorRevision=0,Revision=65536。 - scobi
4
我同意其他人的看法。这实际上并没有回答问题。Gabe的回答才是:https://dev59.com/BnE85IYBdhLWcg3wXCIv#2819974 - Andrew Ensley
4
好的,现在你应该更新表格,加入Windows 8和最新的Windows Server(2012) :) - Davide Piras
1
https://code.msdn.microsoft.com/windowsapps/How-to-determine-the-263b1850 - mja
2
这并不是100%准确的。我正在运行Windows 10 Pro,但它显示为Windows Vista。当我调用API时,它显示我的Win32NT主版本为6。 - user1853517
显示剩余18条评论

64

当我需要确定不同的微软操作系统版本时,我使用了这个:

string getOSInfo()
{
   //Get Operating system information.
   OperatingSystem os = Environment.OSVersion;
   //Get version information about the os.
   Version vs = os.Version;

   //Variable to hold our return value
   string operatingSystem = "";

   if (os.Platform == PlatformID.Win32Windows)
   {
       //This is a pre-NT version of Windows
       switch (vs.Minor)
       {
           case 0:
               operatingSystem = "95";
               break;
           case 10:
               if (vs.Revision.ToString() == "2222A")
                   operatingSystem = "98SE";
               else
                   operatingSystem = "98";
               break;
           case 90:
               operatingSystem = "Me";
               break;
           default:
               break;
       }
   }
   else if (os.Platform == PlatformID.Win32NT)
   {
       switch (vs.Major)
       {
           case 3:
               operatingSystem = "NT 3.51";
               break;
           case 4:
               operatingSystem = "NT 4.0";
               break;
           case 5:
               if (vs.Minor == 0)
                   operatingSystem = "2000";
               else
                   operatingSystem = "XP";
               break;
           case 6:
               if (vs.Minor == 0)
                   operatingSystem = "Vista";
               else if (vs.Minor == 1)
                   operatingSystem = "7";
               else if (vs.Minor == 2)
                   operatingSystem = "8";
               else
                   operatingSystem = "8.1";
               break;
           case 10:
               operatingSystem = "10";
               break;
           default:
               break;
       }
   }
   //Make sure we actually got something in our OS check
   //We don't want to just return " Service Pack 2" or " 32-bit"
   //That information is useless without the OS version.
   if (operatingSystem != "")
   {
       //Got something.  Let's prepend "Windows" and get more info.
       operatingSystem = "Windows " + operatingSystem;
       //See if there's a service pack installed.
       if (os.ServicePack != "")
       {
           //Append it to the OS name.  i.e. "Windows XP Service Pack 3"
           operatingSystem += " " + os.ServicePack;
       }
       //Append the OS architecture.  i.e. "Windows XP Service Pack 3 32-bit"
       //operatingSystem += " " + getOSArchitecture().ToString() + "-bit";
   }
   //Return the information we've gathered.
   return operatingSystem;
}

Source: here


@LonnieBest - 这是一种确定它是x64还是x86的方法...我没有使用它,只是将其注释掉了。 - Gabe
2
vs.Minor != 0 不一定是 XP7。它可能是其中任何一个具有相同次要版本的服务器版本。请参见此处:http://msdn.microsoft.com/en-us/library/windows/desktop/ms724832(v=vs.85).aspx - nawfal
7
我这里有 Windows 10,但显示的信息是 Windows 8。 - Matheus Miranda
6
重要提示:如果您的可执行程序集清单没有明确说明您的exe程序集与Windows 8.1和Windows 10.0兼容,System.Environment.OSVersion将返回Windows 8.0版本。这是6.2,而不是6.3和10.0! - ToolmakerSteve
有关服务器版本,请查看MS的此链接。https://code.msdn.microsoft.com/windowsapps/Sample-to-demonstrate-how-495e69db - daniel.caspers
显示剩余2条评论

32
我使用名为 System.Management 的命名空间下的 ManagementObjectSearcher
示例:
string r = "";
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem"))
{
    ManagementObjectCollection information = searcher.Get();
    if (information != null)
    {
        foreach (ManagementObject obj in information)
        {
            r = obj["Caption"].ToString() + " - " + obj["OSArchitecture"].ToString();
        }
    }
    r = r.Replace("NT 5.1.2600", "XP");
    r = r.Replace("NT 5.2.3790", "Server 2003");
    MessageBox.Show(r);
}
不要忘记添加对程序集 System.Management.dll 的引用,并添加 using: using System.Management;结果:

inserir a descrição da imagem aqui

文档


6
好的,这个回答应该标记为答案,其他解决方案不一致。+1 - Bravo
3
这适用于Windows 11。System.Management是一个NuGet包。 - user10186832

13

这是一个相对较旧的问题,但最近我不得不解决这个问题,没有在任何地方看到我的解决方案。

在我看来,最简单的方法是使用pinvoke调用RtlGetVersion。

[DllImport("ntdll.dll", SetLastError = true)]
internal static extern uint RtlGetVersion(out Structures.OsVersionInfo versionInformation); // return type should be the NtStatus enum

[StructLayout(LayoutKind.Sequential)]
internal struct OsVersionInfo
{
    private readonly uint OsVersionInfoSize;

    internal readonly uint MajorVersion;
    internal readonly uint MinorVersion;

    private readonly uint BuildNumber;

    private readonly uint PlatformId;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
    private readonly string CSDVersion;
}

这个结构体中的主版本号和次版本号对应于已接受答案表格中的值。

与 kernel32 中弃用的 GetVersion 和 GetVersionEx 函数不同,此函数返回正确的 Windows 版本号。


5
在我看来,这是最好的答案。使用.Net的Environment.OSVersion需要操纵清单才能正确工作,而使用WMI则需要引入额外的依赖项。这个方法简单、直接且不复杂。 - Andrew Rondeau
或者更好的方法是使用RtlGetNtVersionNumbers()... 不需要任何结构体。 - Mecanik
如果用户已启用当前应用程序的兼容模式,这是否也会返回正确的版本? - Elmue
我们如何使用这种机制获取操作系统的“ServicePackMajor”、“ServicePackMinor”和版本? - RBT
@RBT 很抱歉回复晚了,这个函数也接受 OSVERSIONINFOEXW 结构体(其中包含您需要的字段),这也是这个答案存在错误的地方 - OsVersionInfoSize 必须在调用之前设置,以便 RtlGetVersionInfo 能够区分这两种结构体类型。 - n0ne

12

.NET 5

从 .NET 5 开始,Environment.OSVersion 方法会返回 Windows 和 macOS 操作系统的实际版本。

var version = Environment.OSVersion;
Console.WriteLine(version);

// Microsoft Windows NT 10.0.19044.0

https://learn.microsoft.com/zh-cn/dotnet/core/compatibility/core-libraries/5.0/environment-osversion-returns-correct-version

旧版本的dotnet:

为确保使用 Environment.OSVersion 获得正确版本,您应该使用 Visual Studio 添加一个 app.manifest 文件,然后取消注释以下 supportedOS 标签:

  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
      <!-- A list of the Windows versions that this application has been tested on
           and is designed to work with. Uncomment the appropriate elements
           and Windows will automatically select the most compatible environment. -->

      <!-- Windows Vista -->
      <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />

      <!-- Windows 7 -->
      <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />

      <!-- Windows 8 -->
      <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />

      <!-- Windows 8.1 -->
      <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />

      <!-- Windows 10 -->
      <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />

    </application>
  </compatibility>

然后你可以这样使用Environment.OSVersion

var version = Environment.OSVersion;
Console.WriteLine(version);

// Before: Microsoft Windows NT 6.2.9200.0
// After: Microsoft Windows NT 10.0.19044.0

例如,在我的机器上(Windows 10.0 Build 19044),如果没有清单文件,结果将是6.2.9200.0,这是不正确的

通过添加app.manifest文件并取消注释这些标签,我将得到正确的版本号,即10.0.19044.0

另一种解决方案

如果您不想将app.manifest添加到项目中,则可以使用OSDescription,它适用于.NET Framework 4.7.1+和.NET Core 1.x+。

// using System.Runtime.InteropServices;
string description = RuntimeInformation.OSDescription;

你可以在这里阅读更多信息,并了解支持的平台。


10

您可以使用这个辅助类;

using System;
using System.Runtime.InteropServices;

/// <summary>
/// Provides detailed information about the host operating system.
/// </summary>
public static class OSInfo
{
    #region BITS
    /// <summary>
    /// Determines if the current application is 32 or 64-bit.
    /// </summary>
    public static int Bits
    {
        get
        {
            return IntPtr.Size * 8;
        }
    }
    #endregion BITS

    #region EDITION
    private static string s_Edition;
    /// <summary>
    /// Gets the edition of the operating system running on this computer.
    /// </summary>
    public static string Edition
    {
        get
        {
            if (s_Edition != null)
                return s_Edition;  //***** RETURN *****//

            string edition = String.Empty;

            OperatingSystem osVersion = Environment.OSVersion;
            OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX();
            osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf( typeof( OSVERSIONINFOEX ) );

            if (GetVersionEx( ref osVersionInfo ))
            {
                int majorVersion = osVersion.Version.Major;
                int minorVersion = osVersion.Version.Minor;
                byte productType = osVersionInfo.wProductType;
                short suiteMask = osVersionInfo.wSuiteMask;

                #region VERSION 4
                if (majorVersion == 4)
                {
                    if (productType == VER_NT_WORKSTATION)
                    {
                        // Windows NT 4.0 Workstation
                        edition = "Workstation";
                    }
                    else if (productType == VER_NT_SERVER)
                    {
                        if ((suiteMask & VER_SUITE_ENTERPRISE) != 0)
                        {
                            // Windows NT 4.0 Server Enterprise
                            edition = "Enterprise Server";
                        }
                        else
                        {
                            // Windows NT 4.0 Server
                            edition = "Standard Server";
                        }
                    }
                }
                #endregion VERSION 4

                #region VERSION 5
                else if (majorVersion == 5)
                {
                    if (productType == VER_NT_WORKSTATION)
                    {
                        if ((suiteMask & VER_SUITE_PERSONAL) != 0)
                        {
                            // Windows XP Home Edition
                            edition = "Home";
                        }
                        else
                        {
                            // Windows XP / Windows 2000 Professional
                            edition = "Professional";
                        }
                    }
                    else if (productType == VER_NT_SERVER)
                    {
                        if (minorVersion == 0)
                        {
                            if ((suiteMask & VER_SUITE_DATACENTER) != 0)
                            {
                                // Windows 2000 Datacenter Server
                                edition = "Datacenter Server";
                            }
                            else if ((suiteMask & VER_SUITE_ENTERPRISE) != 0)
                            {
                                // Windows 2000 Advanced Server
                                edition = "Advanced Server";
                            }
                            else
                            {
                                // Windows 2000 Server
                                edition = "Server";
                            }
                        }
                        else
                        {
                            if ((suiteMask & VER_SUITE_DATACENTER) != 0)
                            {
                                // Windows Server 2003 Datacenter Edition
                                edition = "Datacenter";
                            }
                            else if ((suiteMask & VER_SUITE_ENTERPRISE) != 0)
                            {
                                // Windows Server 2003 Enterprise Edition
                                edition = "Enterprise";
                            }
                            else if ((suiteMask & VER_SUITE_BLADE) != 0)
                            {
                                // Windows Server 2003 Web Edition
                                edition = "Web Edition";
                            }
                            else
                            {
                                // Windows Server 2003 Standard Edition
                                edition = "Standard";
                            }
                        }
                    }
                }
                #endregion VERSION 5

                #region VERSION 6
                else if (majorVersion == 6)
                {
                    int ed;
                    if (GetProductInfo( majorVersion, minorVersion,
                        osVersionInfo.wServicePackMajor, osVersionInfo.wServicePackMinor,
                        out ed ))
                    {
                        switch (ed)
                        {
                            case PRODUCT_BUSINESS:
                                edition = "Business";
                                break;
                            case PRODUCT_BUSINESS_N:
                                edition = "Business N";
                                break;
                            case PRODUCT_CLUSTER_SERVER:
                                edition = "HPC Edition";
                                break;
                            case PRODUCT_DATACENTER_SERVER:
                                edition = "Datacenter Server";
                                break;
                            case PRODUCT_DATACENTER_SERVER_CORE:
                                edition = "Datacenter Server (core installation)";
                                break;
                            case PRODUCT_ENTERPRISE:
                                edition = "Enterprise";
                                break;
                            case PRODUCT_ENTERPRISE_N:
                                edition = "Enterprise N";
                                break;
                            case PRODUCT_ENTERPRISE_SERVER:
                                edition = "Enterprise Server";
                                break;
                            case PRODUCT_ENTERPRISE_SERVER_CORE:
                                edition = "Enterprise Server (core installation)";
                                break;
                            case PRODUCT_ENTERPRISE_SERVER_CORE_V:
                                edition = "Enterprise Server without Hyper-V (core installation)";
                                break;
                            case PRODUCT_ENTERPRISE_SERVER_IA64:
                                edition = "Enterprise Server for Itanium-based Systems";
                                break;
                            case PRODUCT_ENTERPRISE_SERVER_V:
                                edition = "Enterprise Server without Hyper-V";
                                break;
                            case PRODUCT_HOME_BASIC:
                                edition = "Home Basic";
                                break;
                            case PRODUCT_HOME_BASIC_N:
                                edition = "Home Basic N";
                                break;
                            case PRODUCT_HOME_PREMIUM:
                                edition = "Home Premium";
                                break;
                            case PRODUCT_HOME_PREMIUM_N:
                                edition = "Home Premium N";
                                break;
                            case PRODUCT_HYPERV:
                                edition = "Microsoft Hyper-V Server";
                                break;
                            case PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT:
                                edition = "Windows Essential Business Management Server";
                                break;
                            case PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING:
                                edition = "Windows Essential Business Messaging Server";
                                break;
                            case PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY:
                                edition = "Windows Essential Business Security Server";
                                break;
                            case PRODUCT_SERVER_FOR_SMALLBUSINESS:
                                edition = "Windows Essential Server Solutions";
                                break;
                            case PRODUCT_SERVER_FOR_SMALLBUSINESS_V:
                                edition = "Windows Essential Server Solutions without Hyper-V";
                                break;
                            case PRODUCT_SMALLBUSINESS_SERVER:
                                edition = "Windows Small Business Server";
                                break;
                            case PRODUCT_STANDARD_SERVER:
                                edition = "Standard Server";
                                break;
                            case PRODUCT_STANDARD_SERVER_CORE:
                                edition = "Standard Server (core installation)";
                                break;
                            case PRODUCT_STANDARD_SERVER_CORE_V:
                                edition = "Standard Server without Hyper-V (core installation)";
                                break;
                            case PRODUCT_STANDARD_SERVER_V:
                                edition = "Standard Server without Hyper-V";
                                break;
                            case PRODUCT_STARTER:
                                edition = "Starter";
                                break;
                            case PRODUCT_STORAGE_ENTERPRISE_SERVER:
                                edition = "Enterprise Storage Server";
                                break;
                            case PRODUCT_STORAGE_EXPRESS_SERVER:
                                edition = "Express Storage Server";
                                break;
                            case PRODUCT_STORAGE_STANDARD_SERVER:
                                edition = "Standard Storage Server";
                                break;
                            case PRODUCT_STORAGE_WORKGROUP_SERVER:
                                edition = "Workgroup Storage Server";
                                break;
                            case PRODUCT_UNDEFINED:
                                edition = "Unknown product";
                                break;
                            case PRODUCT_ULTIMATE:
                                edition = "Ultimate";
                                break;
                            case PRODUCT_ULTIMATE_N:
                                edition = "Ultimate N";
                                break;
                            case PRODUCT_WEB_SERVER:
                                edition = "Web Server";
                                break;
                            case PRODUCT_WEB_SERVER_CORE:
                                edition = "Web Server (core installation)";
                                break;
                        }
                    }
                }
                #endregion VERSION 6
            }

            s_Edition = edition;
            return edition;
        }
    }
    #endregion EDITION

    #region NAME
    private static string s_Name;
    /// <summary>
    /// Gets the name of the operating system running on this computer.
    /// </summary>
    public static string Name
    {
        get
        {
            if (s_Name != null)
                return s_Name;  //***** RETURN *****//

            string name = "unknown";

            OperatingSystem osVersion = Environment.OSVersion;
            OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX();
            osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf( typeof( OSVERSIONINFOEX ) );

            if (GetVersionEx( ref osVersionInfo ))
            {
                int majorVersion = osVersion.Version.Major;
                int minorVersion = osVersion.Version.Minor;

                switch (osVersion.Platform)
                {
                    case PlatformID.Win32Windows:
                        {
                            if (majorVersion == 4)
                            {
                                string csdVersion = osVersionInfo.szCSDVersion;
                                switch (minorVersion)
                                {
                                    case 0:
                                        if (csdVersion == "B" || csdVersion == "C")
                                            name = "Windows 95 OSR2";
                                        else
                                            name = "Windows 95";
                                        break;
                                    case 10:
                                        if (csdVersion == "A")
                                            name = "Windows 98 Second Edition";
                                        else
                                            name = "Windows 98";
                                        break;
                                    case 90:
                                        name = "Windows Me";
                                        break;
                                }
                            }
                            break;
                        }

                    case PlatformID.Win32NT:
                        {
                            byte productType = osVersionInfo.wProductType;

                            switch (majorVersion)
                            {
                                case 3:
                                    name = "Windows NT 3.51";
                                    break;
                                case 4:
                                    switch (productType)
                                    {
                                        case 1:
                                            name = "Windows NT 4.0";
                                            break;
                                        case 3:
                                            name = "Windows NT 4.0 Server";
                                            break;
                                    }
                                    break;
                                case 5:
                                    switch (minorVersion)
                                    {
                                        case 0:
                                            name = "Windows 2000";
                                            break;
                                        case 1:
                                            name = "Windows XP";
                                            break;
                                        case 2:
                                            name = "Windows Server 2003";
                                            break;
                                    }
                                    break;
                                case 6:
                                    switch (productType)
                                    {
                                        case 1:
                                            name = "Windows Vista";
                                            break;
                                        case 3:
                                            name = "Windows Server 2008";
                                            break;
                                    }
                                    break;
                            }
                            break;
                        }
                }
            }

            s_Name = name;
            return name;
        }
    }
    #endregion NAME

    #region PINVOKE
    #region GET
    #region PRODUCT INFO
    [DllImport( "Kernel32.dll" )]
    internal static extern bool GetProductInfo(
        int osMajorVersion,
        int osMinorVersion,
        int spMajorVersion,
        int spMinorVersion,
        out int edition );
    #endregion PRODUCT INFO

    #region VERSION
    [DllImport( "kernel32.dll" )]
    private static extern bool GetVersionEx( ref OSVERSIONINFOEX osVersionInfo );
    #endregion VERSION
    #endregion GET

    #region OSVERSIONINFOEX
    [StructLayout( LayoutKind.Sequential )]
    private struct OSVERSIONINFOEX
    {
        public int dwOSVersionInfoSize;
        public int dwMajorVersion;
        public int dwMinorVersion;
        public int dwBuildNumber;
        public int dwPlatformId;
        [MarshalAs( UnmanagedType.ByValTStr, SizeConst = 128 )]
        public string szCSDVersion;
        public short wServicePackMajor;
        public short wServicePackMinor;
        public short wSuiteMask;
        public byte wProductType;
        public byte wReserved;
    }
    #endregion OSVERSIONINFOEX

    #region PRODUCT
    private const int PRODUCT_UNDEFINED = 0x00000000;
    private const int PRODUCT_ULTIMATE = 0x00000001;
    private const int PRODUCT_HOME_BASIC = 0x00000002;
    private const int PRODUCT_HOME_PREMIUM = 0x00000003;
    private const int PRODUCT_ENTERPRISE = 0x00000004;
    private const int PRODUCT_HOME_BASIC_N = 0x00000005;
    private const int PRODUCT_BUSINESS = 0x00000006;
    private const int PRODUCT_STANDARD_SERVER = 0x00000007;
    private const int PRODUCT_DATACENTER_SERVER = 0x00000008;
    private const int PRODUCT_SMALLBUSINESS_SERVER = 0x00000009;
    private const int PRODUCT_ENTERPRISE_SERVER = 0x0000000A;
    private const int PRODUCT_STARTER = 0x0000000B;
    private const int PRODUCT_DATACENTER_SERVER_CORE = 0x0000000C;
    private const int PRODUCT_STANDARD_SERVER_CORE = 0x0000000D;
    private const int PRODUCT_ENTERPRISE_SERVER_CORE = 0x0000000E;
    private const int PRODUCT_ENTERPRISE_SERVER_IA64 = 0x0000000F;
    private const int PRODUCT_BUSINESS_N = 0x00000010;
    private const int PRODUCT_WEB_SERVER = 0x00000011;
    private const int PRODUCT_CLUSTER_SERVER = 0x00000012;
    private const int PRODUCT_HOME_SERVER = 0x00000013;
    private const int PRODUCT_STORAGE_EXPRESS_SERVER = 0x00000014;
    private const int PRODUCT_STORAGE_STANDARD_SERVER = 0x00000015;
    private const int PRODUCT_STORAGE_WORKGROUP_SERVER = 0x00000016;
    private const int PRODUCT_STORAGE_ENTERPRISE_SERVER = 0x00000017;
    private const int PRODUCT_SERVER_FOR_SMALLBUSINESS = 0x00000018;
    private const int PRODUCT_SMALLBUSINESS_SERVER_PREMIUM = 0x00000019;
    private const int PRODUCT_HOME_PREMIUM_N = 0x0000001A;
    private const int PRODUCT_ENTERPRISE_N = 0x0000001B;
    private const int PRODUCT_ULTIMATE_N = 0x0000001C;
    private const int PRODUCT_WEB_SERVER_CORE = 0x0000001D;
    private const int PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT = 0x0000001E;
    private const int PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY = 0x0000001F;
    private const int PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING = 0x00000020;
    private const int PRODUCT_SERVER_FOR_SMALLBUSINESS_V = 0x00000023;
    private const int PRODUCT_STANDARD_SERVER_V = 0x00000024;
    private const int PRODUCT_ENTERPRISE_SERVER_V = 0x00000026;
    private const int PRODUCT_STANDARD_SERVER_CORE_V = 0x00000028;
    private const int PRODUCT_ENTERPRISE_SERVER_CORE_V = 0x00000029;
    private const int PRODUCT_HYPERV = 0x0000002A;
    #endregion PRODUCT

    #region VERSIONS
    private const int VER_NT_WORKSTATION = 1;
    private const int VER_NT_DOMAIN_CONTROLLER = 2;
    private const int VER_NT_SERVER = 3;
    private const int VER_SUITE_SMALLBUSINESS = 1;
    private const int VER_SUITE_ENTERPRISE = 2;
    private const int VER_SUITE_TERMINAL = 16;
    private const int VER_SUITE_DATACENTER = 128;
    private const int VER_SUITE_SINGLEUSERTS = 256;
    private const int VER_SUITE_PERSONAL = 512;
    private const int VER_SUITE_BLADE = 1024;
    #endregion VERSIONS
    #endregion PINVOKE

    #region SERVICE PACK
    /// <summary>
    /// Gets the service pack information of the operating system running on this computer.
    /// </summary>
    public static string ServicePack
    {
        get
        {
            string servicePack = String.Empty;
            OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX();

            osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf( typeof( OSVERSIONINFOEX ) );

            if (GetVersionEx( ref osVersionInfo ))
            {
                servicePack = osVersionInfo.szCSDVersion;
            }

            return servicePack;
        }
    }
    #endregion SERVICE PACK

    #region VERSION
    #region BUILD
    /// <summary>
    /// Gets the build version number of the operating system running on this computer.
    /// </summary>
    public static int BuildVersion
    {
        get
        {
            return Environment.OSVersion.Version.Build;
        }
    }
    #endregion BUILD

    #region FULL
    #region STRING
    /// <summary>
    /// Gets the full version string of the operating system running on this computer.
    /// </summary>
    public static string VersionString
    {
        get
        {
            return Environment.OSVersion.Version.ToString();
        }
    }
    #endregion STRING

    #region VERSION
    /// <summary>
    /// Gets the full version of the operating system running on this computer.
    /// </summary>
    public static Version Version
    {
        get
        {
            return Environment.OSVersion.Version;
        }
    }
    #endregion VERSION
    #endregion FULL

    #region MAJOR
    /// <summary>
    /// Gets the major version number of the operating system running on this computer.
    /// </summary>
    public static int MajorVersion
    {
        get
        {
            return Environment.OSVersion.Version.Major;
        }
    }
    #endregion MAJOR

    #region MINOR
    /// <summary>
    /// Gets the minor version number of the operating system running on this computer.
    /// </summary>
    public static int MinorVersion
    {
        get
        {
            return Environment.OSVersion.Version.Minor;
        }
    }
    #endregion MINOR

    #region REVISION
    /// <summary>
    /// Gets the revision version number of the operating system running on this computer.
    /// </summary>
    public static int RevisionVersion
    {
        get
        {
            return Environment.OSVersion.Version.Revision;
        }
    }
    #endregion REVISION
    #endregion VERSION
}

这是示例代码:

    Console.WriteLine( "Operation System Information" );
    Console.WriteLine( "----------------------------" );
    Console.WriteLine( "Name = {0}", OSInfo.Name );
    Console.WriteLine( "Edition = {0}", OSInfo.Edition );
    Console.WriteLine( "Service Pack = {0}", OSInfo.ServicePack );
    Console.WriteLine( "Version = {0}", OSInfo.VersionString );
    Console.WriteLine( "Bits = {0}", OSInfo.Bits );

我被发现在这个地址:http://www.csharp411.com/wp-content/uploads/2009/01/OSInfo.cs


是的,这段代码对于主版本6来说是不完整的。它需要在产品类型上已有的开关之外,再增加一个关于次版本的开关。(对于不同的产品类型,6.0和6.1具有不同的含义。) - ladenedge
4
你是从这里拿的吗:http://www.csharp411.com/wp-content/uploads/2009/01/OSInfo.cs?请注明出处。 - nawfal
1
请注意,版本信息列表已过时。更新的列表可以在以下网址找到:https://msdn.microsoft.com/zh-cn/library/windows/desktop/ms724358(v=vs.85).aspx - Sean Duggan

8
根据 R. Bemrose 的建议,如果你正在使用 Windows 7 特定功能,可以查看 Microsoft® .NET Framework 的 Windows® API Code Pack
它包含一个 CoreHelpers 类,可让您确定当前所在的操作系统(仅限 XP 及以上版本,这是现今 .NET 的要求)。
它还提供了多个辅助方法。例如,假设您想使用 Windows 7 的跳转列表,则有一个名为 TaskbarManager 的类,它提供了一个名为 IsPlatformSupported 的属性,如果您正在使用 Windows 7 或更高版本,则它将返回 true。

7

通过 Environment.OSVersion 获取一个包含当前平台标识符和版本号的 System.OperatingSystem 对象。


5
这个问题可以追溯到Windows XP时代,问题和答案经过多年的编辑。
以下代码使用.NET Framework工作,并应该检测到所有版本的Windows 10。
基于这个问题和答案 - ( 如何在.NET 5.0控制台应用程序中使用C#检查Windows版本 )
using System;
using Microsoft.Win32;

namespace WindowsVersion
{
    class Version
    {
        static void Main(string[] args)
        {
            string HKLMWinNTCurrent = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion";
            string osName = Registry.GetValue(HKLMWinNTCurrent, "productName", "").ToString();
            string osRelease = Registry.GetValue(HKLMWinNTCurrent, "ReleaseId", "").ToString();
            string osVersion = Environment.OSVersion.Version.ToString();
            string osType = Environment.Is64BitOperatingSystem ? "64-bit" : "32-bit";
            string osBuild = Registry.GetValue(HKLMWinNTCurrent, "CurrentBuildNumber", "").ToString();
            string osUBR = Registry.GetValue(HKLMWinNTCurrent, "UBR", "").ToString();
            Console.WriteLine("OS Name:" + osName);
            Console.WriteLine("OS Release:" + osRelease);
            Console.WriteLine("OS Version:" + osVersion);
            Console.WriteLine("OS Type:" + osType);
            Console.WriteLine("OS Build:" + osBuild);
            Console.WriteLine("OS UBR:" + osUBR);
            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }
    }
}

我已在我的电脑上测试过,结果如下。

result

请查看维基百科文章以获取Windows 10版本列表。

https://en.wikipedia.org/wiki/List_of_Microsoft_Windows_versions

Windows 11更新

根据此链接,目前在注册表中没有存储Windows产品名称的位置。

https://learn.microsoft.com/en-us/answers/questions/555857/windows-11-product-name-in-registry.html

作为一种解决方法,请使用以下代码片段 -
    if (osBuild == "22000")
    {
        osFullName = "Windows 11";
    }

在我的电脑上,它报告了Windows 10和Windows 11。

2
这是一个完全可靠的答案,可以在所有情况下提供准确的信息。唯一需要注意的是,您的应用程序可能需要管理员权限才能访问注册表。还有一些其他有用的键,例如InstallationType(客户端/服务器)、CurrentMajorVersionNumber、CurrentMinorVersionNumber、EditionID(企业版、专业版、家庭版等),任何人都可以利用它们。 - RBT

4
检测操作系统版本:
    public static string OS_Name()
    {
        return (string)(from x in new ManagementObjectSearcher(
            "SELECT Caption FROM Win32_OperatingSystem").Get().Cast<ManagementObject>() 
            select x.GetPropertyValue("Caption")).FirstOrDefault();
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接