news new microsoft last features docs compute c# .net operating-system windowsversion

new - Versión de Windows en c#



named tuples c# (4)

Esta pregunta ya tiene una respuesta aquí:

Quiero saber qué versión de Windows tiene la PC ... en C # Framework 3.5

He intentado usar

OperatingSystem os = Environment.OSVersion;

Versión ver = os.Version;

Pero el resultado es

Plataforma: WIN32NT

versión 6.2.9200

Versión menor: 2

Versión Major: 6

El problema es que tengo "Windows 8 Pro" ...

¿Cómo puedo detectarlo?

Gracias


Lancé el Nuget OsInfo para comparar fácilmente las versiones de Windows.

bool win8OrLess = Environment.OSVersion.IsLessThanOrEqualTo(OsVersion.Win8); bool winXp = Environment.OSVersion.IsEqualTo(OsVersion.WinXP); int? servicePack = Environment.OSVersion.GetServicePackVersion(); bool is64bit = Environment.OSVersion.Is64Bit(); // Already covered in .NET 4.5+


Tendrá que hacer coincidir los números de versión con el valor de cadena apropiado usted mismo.

Aquí hay una lista del sistema operativo Windows más reciente y su número de versión correspondiente:

  • Vista previa técnica de Windows Server 2016 - 10.0 *
  • Windows 10 - 10.0 *
  • Windows 8.1 - 6.3 *
  • Windows Server 2012 R2 - 6.3 *
  • Windows 8 - 6.2
  • Windows Server 2012 - 6.2
  • Windows 7 - 6.1
  • Windows Server 2008 R2 - 6.1
  • Windows Server 2008 - 6.0
  • Windows Vista - 6.0
  • Windows Server 2003 R2 - 5.2
  • Windows Server 2003 - 5.2
  • Windows XP 64-Bit Edition - 5.2
  • Windows XP - 5.1
  • Windows 2000 - 5.0

* Para aplicaciones que se han manifestado para Windows 8.1 o 10. Las aplicaciones no manifestadas para 8.1 / 10 devolverán el valor de versión del sistema operativo Windows 8 (6.2).

Aquí está la fuente .

Además, de la misma fuente:

Identificar el sistema operativo actual generalmente no es la mejor manera de determinar si una característica particular del sistema operativo está presente. Esto se debe a que el sistema operativo puede tener nuevas características agregadas en una DLL redistribuible. En lugar de utilizar las funciones de Version API Helper para determinar la plataforma del sistema operativo o el número de versión, verifique la presencia de la función en sí.


En mi caso, necesitaba mi aplicación para capturar información de la computadora para posibles informes de errores y estadísticas.

No encontré las soluciones donde un manifiesto de la aplicación tenía que ser agregado satisfactorio. La mayoría de las sugerencias que encontré mientras busqué en Google sugirieron eso, desafortunadamente.

La cosa es que, cuando se utiliza un manifiesto, cada versión del sistema operativo debe agregarse manualmente para que esa versión del sistema operativo en particular pueda informarse en tiempo de ejecución.

En otras palabras, esto se convierte en una condición de carrera: un usuario de mi aplicación puede estar usando una versión de mi aplicación que es anterior al SO en uso. Tendría que actualizar la aplicación inmediatamente cuando Microsoft lanzó una nueva versión del sistema operativo. También tendría que forzar a los usuarios a actualizar la aplicación al mismo tiempo que actualizaron el sistema operativo.

En otras palabras, no es muy factible .

Después de navegar a través de las opciones, encontré algunas referencias (sorprendentemente pocas en comparación con el manifiesto de la aplicación) que sugerían usar búsquedas de registro.

Mi clase ComputerInfo (cortada) con solo WinMajorVersion , WinMinorVersion y IsServer propiedades de IsServer ve así:

using Microsoft.Win32; namespace Inspection { /// <summary> /// Static class that adds convenient methods for getting information on the running computers basic hardware and os setup. /// </summary> public static class ComputerInfo { /// <summary> /// Returns the Windows major version number for this computer. /// </summary> public static uint WinMajorVersion { get { dynamic major; // The ''CurrentMajorVersionNumber'' string value in the CurrentVersion key is new for Windows 10, // and will most likely (hopefully) be there for some time before MS decides to change this - again... if (TryGeRegistryKey(@"SOFTWARE/Microsoft/Windows NT/CurrentVersion", "CurrentMajorVersionNumber", out major)) { return (uint) major; } // When the ''CurrentMajorVersionNumber'' value is not present we fallback to reading the previous key used for this: ''CurrentVersion'' dynamic version; if (!TryGeRegistryKey(@"SOFTWARE/Microsoft/Windows NT/CurrentVersion", "CurrentVersion", out version)) return 0; var versionParts = ((string) version).Split(''.''); if (versionParts.Length != 2) return 0; uint majorAsUInt; return uint.TryParse(versionParts[0], out majorAsUInt) ? majorAsUInt : 0; } } /// <summary> /// Returns the Windows minor version number for this computer. /// </summary> public static uint WinMinorVersion { get { dynamic minor; // The ''CurrentMinorVersionNumber'' string value in the CurrentVersion key is new for Windows 10, // and will most likely (hopefully) be there for some time before MS decides to change this - again... if (TryGeRegistryKey(@"SOFTWARE/Microsoft/Windows NT/CurrentVersion", "CurrentMinorVersionNumber", out minor)) { return (uint) minor; } // When the ''CurrentMinorVersionNumber'' value is not present we fallback to reading the previous key used for this: ''CurrentVersion'' dynamic version; if (!TryGeRegistryKey(@"SOFTWARE/Microsoft/Windows NT/CurrentVersion", "CurrentVersion", out version)) return 0; var versionParts = ((string) version).Split(''.''); if (versionParts.Length != 2) return 0; uint minorAsUInt; return uint.TryParse(versionParts[1], out minorAsUInt) ? minorAsUInt : 0; } } /// <summary> /// Returns whether or not the current computer is a server or not. /// </summary> public static uint IsServer { get { dynamic installationType; if (TryGeRegistryKey(@"SOFTWARE/Microsoft/Windows NT/CurrentVersion", "InstallationType", out installationType)) { return (uint) (installationType.Equals("Client") ? 0 : 1); } return 0; } } private static bool TryGeRegistryKey(string path, string key, out dynamic value) { value = null; try { var rk = Registry.LocalMachine.OpenSubKey(path); if (rk == null) return false; value = rk.GetValue(key); return value != null; } catch { return false; } } } }


Prueba esto:

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

Fuente: https://.com/a/2016557/3273962