获取Service Pack主要版本

时间:2013-07-19 18:04:33

标签: c# operating-system version

在Environment.OSVersion.ServicePack中我只看到ServicePack变量,但没有主要版本或次要版本,我如何获得主要版本或次要版本?

2 个答案:

答案 0 :(得分:2)

您可以使用以下代码。

    void Main()
    {
        GetServicePackVersion().Major.Dump();
    }

    [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;
    }

    [DllImport("kernel32.dll")]
    private static extern bool GetVersionEx([In, Out] ref OSVERSIONINFOEX osVersionInfo);

    public static Version GetServicePackVersion()
    {
        OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX();
        osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf(typeof(OSVERSIONINFOEX));

        if (GetVersionEx(ref osVersionInfo))
        {
            Version result = new Version(osVersionInfo.wServicePackMajor, osVersionInfo.wServicePackMinor);
            return result;
        }
        else
        {
            return null;
        }
    }

答案 1 :(得分:-1)

Service Pack没有主要版本或次要版本。您必须浏览Environment.OSVersion.Version以获取必要的版本信息。