简体   繁体   中英

How to check windows version in C# on .NET 5.0 console app

Like im working on a "console game engine" but it only works on Windows 10 since "custom colors" arent properly displayed on other versions, for example win8, instead they are just a bunch of unicode codes? "

例子.png "

so i wanna check if windows version is 10. and i did this

var workingSysVer = Environment.OSVersion.Version.ToString().Substring(0, 2);
            if (workingSysVer != "10")
            {
                Console.Title = "OS Version Warning";
                // other code
            }

Is there a better way to check version of windows?

You can use what you need from this (in addition to OSVersion you can use osName and osRelease ):

using System;
using System.Linq;
using System.Reflection;
using System.Runtime.Versioning;
using Microsoft.Win32;

string NL = Environment.NewLine;
string HKLMWinNTCurrent = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion";

string osName = get(() => Registry.GetValue(HKLMWinNTCurrent, "productName", "").ToString());

string osRelease = get(() => Registry.GetValue(HKLMWinNTCurrent, "ReleaseId", "").ToString());
if ( !osRelease.IsNullOrEmpty() ) osRelease = $" ({ osRelease})";

string osVersion = Environment.OSVersion.Version.ToString();

string osType = Environment.Is64BitOperatingSystem ? "64-bits" : "32-bits";

string clr = Environment.Version.ToString();

string dotnet = get(() =>
{
  var attributes = Assembly.GetExecutingAssembly().CustomAttributes;
  var result = attributes.FirstOrDefault(a => a.AttributeType == typeof(TargetFrameworkAttribute));
  return result == null
          ? ".NET Framework (unknown)"
          : result.NamedArguments[0].TypedValue.Value.ToString();
});

string Platform = $"{osName} {osType} {osVersion}{osRelease}{NL}{dotnet}{NL}CLR {clr}";

string get(Func<string> func)
{
  try { return func(); }
  catch { return "(undefined)"; }
}

Example

Windows 10 Pro 64-bits 6.2.9200.0 (2009)
.NET Framework 4.7.2
CLR 4.0.30319.42000

I never noticed that 6.2.9200 is incorrect ... ??

Solution from @nap : How to get Windows Version - as in "Windows 10, version 1607"?

Explanation from @DanielDiPaolo : Detect Windows version in .net

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM