在C#中获取Windows 10当前版本的操作系统

5

我使用C#。我尝试获取当前操作系统的版本:

OperatingSystem os = Environment.OSVersion;
Version ver = os.Version;

我使用的是Windows 10操作系统:6.2

6.2实际上是指Windows 8WindowsServer 2012.net中检测Windows版本)。

我找到了以下解决方案(如何检测我的应用程序是否在运行Windows 10)。

static bool IsWindows10()
{
  var reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
  string productName = (string)reg.GetValue("ProductName");
  return productName.StartsWith("Windows 10");
}

这是在C#中获取当前版本的最佳方法吗?


1
也许可以看看这个链接:https://dev59.com/MWw15IYBdhLWcg3w4_7k - Martin Verjans
1
@olga,你添加了清单+supportedOS指南吗? - magicandre1981
3个回答

10

应用程序清单添加到您的应用程序中,并将 Windows 8.1 和 Windows 10 的supportedOS Id添加到清单中:

<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}"/>
        </application> 
    </compatibility>

现在Environment.OSVersion包括正确的Windows 8.1和Windows 10数据,而不是6.2来表示您运行的是Windows 8。自从Windows 8.1以来就进行了此更改。


0

这里有一个来自微软官方的链接,指示如何获取系统版本(how to get the System Version)。实际上,它是对版本 API 帮助函数(Version API Helper Functions)的调用。

因此,基本上你必须将这段代码转换为 C#,因为它是用 C++ 编写的,然后只保留 Windows 10 部分...

#include <windows.h>
#include <stdio.h>
#include <VersionHelpers.h>

int 
__cdecl
wmain(
    __in int argc, 
    __in_ecount(argc) PCWSTR argv[]
    )
{
    UNREFERENCED_PARAMETER(argc);
    UNREFERENCED_PARAMETER(argv);
    if (IsWindows10OrGreater())
    {
        printf("Windows10OrGreater\n");
    }
}

如果你喜欢阅读代码,可以查看 这个链接。这个 DLL 可以用于获取操作系统的信息...


0

我已经在C#中创建了这个简单的方法,并且它对我很有效。

    public static string GetWindowsVersion()
    {
        string registryPath = "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows NT\\CurrentVersion";
        string build = null;
        int number = 0;

        try
        {
            build = Registry.GetValue(registryPath, "CurrentBuild", null).ToString();
        }
        catch { return null; }

        number = Int32.Parse(build);

        if (number == 7601)
            return "Windows 7";
        else if (number == 9200)
            return "Windows 8";
        else if (number == 9600)
            return "Windows 8.1";
        else if (number >= 10240 && number <= 19045)
            return "Windows 10";
        else if (number >= 22000)
            return "Windows 11";
        else
            return "Older version";

        /* Go here to find more build numbers and evaluate more conditions
         * 
         * https://en.wikipedia.org/wiki/List_of_Microsoft_Windows_versions
         * 
         */ 
    }

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