如何检测Windows 8操作系统使用C#4.0?

我必须在我的C#Windows应用程序中检测Windows 8操作系统并执行一些设置。 我知道我们可以使用Environment.OSVersion检测Windows 7,但是如何检测Windows 8?

提前致谢。

 Version win8version = new Version(6, 2, 9200, 0); if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version >= win8version) { // its win8 or higher. } 

更新的Windows 8.1和更高版本:

好吧,在我看来,这段代码已经被微软自己弃用了。 我在这里留下一个链接,所以你可以阅读更多关于它。

总之,它说:

对于Windows 8和更高版本,总是会有相同的版本号(6,2,9200,0) 。 而不是寻找Windows版本,去寻找你正试图解决的实际功能。

Windows 8或更新版本:

 bool IsWindows8OrNewer() { var os = Environment.OSVersion; return os.Platform == PlatformID.Win32NT && (os.Version.Major > 6 || (os.Version.Major == 6 && os.Version.Minor >= 2)); } 

检查以下问题的答案: 如何获得“友好的”操作系统版本名称?

引用回答:

您可以使用WMI获取产品名称(“Microsoft®Windowsserver®2008 Enterprise”):

 using System.Management; var name = (from x in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem").Get().OfType<ManagementObject>() select x.GetPropertyValue("Caption")).First(); return name != null ? name.ToString() : "Unknown"; 

首先声明一个结构如下:

 [StructLayout(LayoutKind.Sequential)] public struct OsVersionInfoEx { public int dwOSVersionInfoSize; public uint dwMajorVersion; public uint dwMinorVersion; public uint dwBuildNumber; public uint dwPlatformId; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string szCSDVersion; public UInt16 wServicePackMajor; public UInt16 wServicePackMinor; public UInt16 wSuiteMask; public byte wProductType; public byte wReserved; } 

你将需要这个使用声明:

  using System.Runtime.InteropServices; 

在相关课程的顶部,声明:

  [DllImport("kernel32", EntryPoint = "GetVersionEx")] static extern bool GetVersionEx(ref OsVersionInfoEx osVersionInfoEx); 

现在调用代码如下:

  const int VER_NT_WORKSTATION = 1; var osInfoEx = new OsVersionInfoEx(); osInfoEx.dwOSVersionInfoSize = Marshal.SizeOf(osInfoEx); try { if (!GetVersionEx(ref osInfoEx)) { throw(new Exception("Could not determine OS Version")); } if (osInfoEx.dwMajorVersion == 6 && osInfoEx.dwMinorVersion == 2 && osInfoEx.wProductType == VER_NT_WORKSTATION) MessageBox.Show("You've Got windows 8"); } catch (Exception) { throw; } 

不知道这是否正确,因为我只能检查我的Windows 8的版本。

  int major = Environment.OSVersion.Version.Major; int minor = Environment.OSVersion.Version.Minor; if ((major >= 6) && (minor >= 2)) { //do work here }