【问题标题】:How can I detect which version of Windows is running?如何检测正在运行的 Windows 版本?
【发布时间】:2015-09-17 08:38:40
【问题描述】:

我有一个作为 Word 插件运行的应用程序。 (VSTO)。

它可以在世界各地的许多 PC 上运行。在某些情况下,我需要解决问题(显然是远程)并有一个报告机制来告诉我正在运行哪个 Windows 操作系统 - 我在 .NET 中使用Environment.OSVersion。至少在 Windows 10 之前是这样。

在 MSDN (Targeting your application for Windows) 上有一篇关于创建应用程序清单的文章,该清单将能够返回正确的版本。

但我的应用程序是 DLL,而不是 EXE,因此不能真正适应那篇文章中提到的 XML 代码。

没有办法只问Windows,“你是什么版本?真的,如果你承认真实版本,我不会哭”。

或者注册表中的条目或其他什么?

【问题讨论】:

  • 顺便说一句——你为什么关心你运行的是什么版本? (特别是 Windows 10 会有不同的版本)
  • 我只是希望能够缩小发生错误的情况。并且知道操作系统对此有什么帮助。也许某个特定错误只发生在 Windows 10 上 - 很高兴知道这一点。
  • 纯粹是为了防止人们通过本地友好的搜索引擎查找有关 Windows 10 版本的信息:对于通用应用程序,有一个 good blog post on feature detection
  • 谢谢 Kevin Kal - 这给了我想要的东西。

标签: c# windows


【解决方案1】:

如果 WMI 不适合您,您可以使用 GetVersionEx 函数的 SDK 对应项 RtlGetVersion。他们不会说谎。

如果您使用 .NET 5.0 或 Core,Environment.OSVersion 会报告 Windows 的实际版本。

我发布了有关此问题的更多详细信息,作为其他线程答案的补充: https://stackoverflow.com/a/64804643/2240196

编辑:根据要求添加了示例代码。 (你可能不需要全部)

using System;
using System.Runtime.InteropServices;

namespace VersionHelper
{
    public static class VersionHelper
    {
        // The C(++) macro VER_SET_CONDITION mentioned in the documentation for RtlVerifyVersionInfo seems to be equivalent to the VerSetConditionMask function in kernel32.dll

        // https://docs.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-versetconditionmask
        [DllImport("kernel32.dll")]
        private static extern ulong VerSetConditionMask(ulong dwlConditionMask, uint dwTypeBitMask, byte dwConditionMask);

        // https://docs.microsoft.com/en-us/windows/win32/devnotes/rtlgetversion
        [DllImport("ntdll.dll")]
        private static extern int RtlGetVersion(ref OSVERSIONINFOW lpVersionInformation);

        [DllImport("ntdll.dll")]
        private static extern int RtlGetVersion(ref OSVERSIONINFOEXW lpVersionInformation);

        // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlverifyversioninfo
        [DllImport("ntdll.dll")]
        private static extern bool RtlVerifyVersionInfo([In] ref OSVERSIONINFOEXW lpVersionInformation, uint dwTypeMask, ulong dwlConditionMask);

        // https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-osversioninfoexw
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        private struct OSVERSIONINFOEXW
        {
            internal uint dwOSVersionInfoSize;
            internal uint dwMajorVersion;
            internal uint dwMinorVersion;
            internal uint dwBuildNumber;
            internal uint dwPlatformId;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
            internal string szCSDVersion;
            internal ushort wServicePackMajor;
            internal ushort wServicePackMinor;
            internal ushort wSuiteMask;
            internal byte wProductType;
            internal byte wReserved;
        }
        
        // https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-osversioninfow
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        private struct OSVERSIONINFOW
        {
            internal uint dwOSVersionInfoSize;
            internal uint dwMajorVersion;
            internal uint dwMinorVersion;
            internal uint dwBuildNumber;
            internal uint dwPlatformId;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
            internal string szCSDVersion;
        }

        /*
         * RTL_OSVERSIONINFOEX(A/W) and OSVERSIONINFOEX(A/W) are aliases for the same structures
         * RTL_OSVERSIONINFO(A/W) and OSVERSIONINFO(A/W) are aliases for the same structures
         * */

        // These constants initialized with corresponding definitions in
        // winnt.h (part of Windows SDK)
        // https://docs.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-ver_set_condition
        private const byte VER_EQUAL = 1;
        private const byte VER_GREATER = 2;
        private const byte VER_GREATER_EQUAL = 3;
        private const byte VER_LESS = 4;
        private const byte VER_LESS_EQUAL = 5;
        private const byte VER_AND = 6;
        private const byte VER_OR = 7;

        private const byte VER_CONDITION_MASK = 7;
        private const byte VER_NUM_BITS_PER_CONDITION_MASK = 3;

        private const uint STATUS_SUCCESS = 0x00000000;

        //
        // RtlVerifyVersionInfo() type mask bits
        //
        private const uint VER_MINORVERSION = 0x0000001;
        private const uint VER_MAJORVERSION = 0x0000002;
        private const uint VER_BUILDNUMBER = 0x0000004;
        private const uint VER_PLATFORMID = 0x0000008;
        private const uint VER_SERVICEPACKMINOR = 0x0000010;
        private const uint VER_SERVICEPACKMAJOR = 0x0000020;
        private const uint VER_SUITENAME = 0x0000040;
        private const uint VER_PRODUCT_TYPE = 0x0000080;

        // wProductType    
        // Any additional information about the system.This member can be one of the following values.
        private const byte VER_NT_DOMAIN_CONTROLLER = 0x0000002;
        private const byte VER_NT_SERVER = 0x0000003;
        private const byte VER_NT_WORKSTATION = 0x0000001;


        // You can customize this to check for the condition(s) you need using any field from the OSVERSIONINFOW struct with the corresponding VER_ and VER_<operator> constants
        public static bool IsWindowsVersionOrGreater(uint majorVersion, uint minorVersion, ushort servicePackMajor = 0, uint buildNumber = 0)
        {
            var osVerInfo = new OSVERSIONINFOEXW
            {
                dwOSVersionInfoSize = (uint) Marshal.SizeOf(typeof(OSVERSIONINFOEXW)),
                dwMajorVersion = majorVersion,
                dwMinorVersion = minorVersion,
                wServicePackMajor = servicePackMajor,
                dwBuildNumber = buildNumber
            };
            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;
            if (buildNumber > 0)
            {
                versionOrGreaterMask = VerSetConditionMask(versionOrGreaterMask, VER_BUILDNUMBER, VER_GREATER_EQUAL);
                versionOrGreaterTypeMask |= VER_BUILDNUMBER;
            }
            return RtlVerifyVersionInfo(ref osVerInfo, versionOrGreaterTypeMask, versionOrGreaterMask);
        }

        public static bool IsWindowsServer()
        {
            var osVerInfo = new OSVERSIONINFOEXW
            {
                dwOSVersionInfoSize = (uint) Marshal.SizeOf(typeof(OSVERSIONINFOEXW)),
                wProductType = VER_NT_WORKSTATION
            };
            ulong dwlConditionMask = VerSetConditionMask(0, VER_PRODUCT_TYPE, VER_EQUAL);
            return !RtlVerifyVersionInfo(ref osVerInfo, VER_PRODUCT_TYPE, dwlConditionMask);
        }
        
        public static int GetWindowsBuildNumber()
        {
            var osVerInfo = new OSVERSIONINFOW
            {
                dwOSVersionInfoSize = (uint) Marshal.SizeOf(typeof(OSVERSIONINFOW))
            };
            if (STATUS_SUCCESS == RtlGetVersion(ref osVerInfo)) // documented to always return STATUS_SUCCESS
                return (int)osVerInfo.dwBuildNumber;
            throw new Win32Exception("Failed to determine Windows build number.");
        }

        // Other functions replicating SDK Version Helper functions
        // https://docs.microsoft.com/en-us/windows/win32/sysinfo/version-helper-apis

        //
        // _WIN32_WINNT version constants
        //
        const ushort _WIN32_WINNT_NT4 = 0x0400;
        const ushort _WIN32_WINNT_WIN2K = 0x0500;
        const ushort _WIN32_WINNT_WINXP = 0x0501;
        const ushort _WIN32_WINNT_WS03 = 0x0502;
        const ushort _WIN32_WINNT_WIN6 = 0x0600;
        const ushort _WIN32_WINNT_VISTA = 0x0600;
        const ushort _WIN32_WINNT_WS08 = 0x0600;
        const ushort _WIN32_WINNT_LONGHORN = 0x0600;
        const ushort _WIN32_WINNT_WIN7 = 0x0601;
        const ushort _WIN32_WINNT_WIN8 = 0x0602;
        const ushort _WIN32_WINNT_WINBLUE = 0x0603;
        const ushort _WIN32_WINNT_WINTHRESHOLD = 0x0A00; 
        const ushort _WIN32_WINNT_WIN10 = 0x0A00;

        const bool FALSE = false;

        static byte LOBYTE(ushort w)
        {
            return ((byte)(w & 0xff));
        }

        static byte HIBYTE(ushort w)
        {
            return ((byte)(w >> 8 & 0xff));
        }

        public static bool
        IsWindowsXPSP1OrGreater()
        {
            return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINXP), LOBYTE(_WIN32_WINNT_WINXP), 1);
        }

        public static bool
        IsWindowsXPSP2OrGreater()
        {
            return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINXP), LOBYTE(_WIN32_WINNT_WINXP), 2);
        }

        public static bool
        IsWindowsXPSP3OrGreater()
        {
            return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINXP), LOBYTE(_WIN32_WINNT_WINXP), 3);
        }

        public static bool
        IsWindowsVistaOrGreater()
        {
            return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA), 0);
        }

        public static bool
        IsWindowsVistaSP1OrGreater()
        {
            return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA), 1);
        }

        public static bool
        IsWindowsVistaSP2OrGreater()
        {
            return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA), 2);
        }

        public static bool
        IsWindows7OrGreater()
        {
            return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN7), LOBYTE(_WIN32_WINNT_WIN7), 0);
        }

        public static bool
        IsWindows7SP1OrGreater()
        {
            return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN7), LOBYTE(_WIN32_WINNT_WIN7), 1);
        }

        public static bool
        IsWindows8OrGreater()
        {
            return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN8), LOBYTE(_WIN32_WINNT_WIN8), 0);
        }

        public static bool
        IsWindows8Point1OrGreater()
        {
            return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINBLUE), LOBYTE(_WIN32_WINNT_WINBLUE), 0);
        }

        public static bool
        IsWindows10OrGreater()
        {
            return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN10), LOBYTE(_WIN32_WINNT_WIN10), 0);
        }
    }
}

【讨论】:

  • 请不要仅使用链接回答。请提供一些带有上下文的示例。以后链接可能失效了,你的回答就没用了
  • @AmirhosseinYari 感谢您的反馈。我添加了一些代码。我希望这能提供足够的上下文信息。
【解决方案2】:
private String GetOSVersion()
{
    var wmiEnum = new ManagementObjectSearcher("root\\CIMV2", "SELECT Version FROM  Win32_OperatingSystem").Get().GetEnumerator();
    wmiEnum.MoveNext();
    return wmiEnum.Current.Properties["Version"].Value as String;
}

在我的 W7 系统上返回 6.1.7601,在我的 Server 2016 系统上返回 10.0.14393。

无需添加目标清单。

【讨论】:

    【解决方案3】:

    WMI 是执行此类操作的最佳方式您可以使用它来检索操作系统信息:

    ManagementObjectSearcher objMOS = 
           new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM  Win32_OperatingSystem");
    
    OS.Name = ((string)objMOS["Caption"]).Trim();
    OS.Version = (string)objMOS["Version"];
    OS.MaxProcessCount = (uint)objMOS["MaxNumberOfProcesses"];
    OS.MaxProcessRAM = (ulong)objMOS["MaxProcessMemorySize"];
    OS.Architecture = (string)objMOS["OSArchitecture"];
    OS.SerialNumber = (string)objMOS["SerialNumber"];
    OS.Build = ((string)objMOS["BuildNumber"]).ToUint();
    

    这可以为您获取操作系统详细信息。

    【讨论】:

    • @Mohti,您的代码不起作用,这就是我所知道的。我的编码技能不熟练
    • @Mohit Black 是对的。你的代码很垃圾。感谢您浪费我的时间和其他偶然发现此问题的人的时间。
    【解决方案4】:

    你可以试试GetVersionEx Win32 API。

    https://msdn.microsoft.com/en-us/library/windows/desktop/ms724451(v=vs.85).aspx

    请注意,Windows 10 实际上是 6.4 版。版本 6.0 是 Vista、6.1 - 7、6.2 - 8。

    【讨论】:

    • 这仅在您拥有适当的清单条目时才有效。否则,它只会是彻头彻尾的谎言,告诉你一切都是 Windows 8。
    猜你喜欢
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    相关资源
    最近更新 更多