Comment puis-je déterminer sur quel système d’exploitation mon application .NET Core est exécutée? Dans le passé, je pouvais utiliser Environment.OSVersion
.
Quel est le moyen actuel de déterminer si mon application s’exécute sur Mac ou Windows?
System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform()
OSPlatform.Windows OSPlatform.OSX OSPlatform.Linux
bool isWindows = System.Runtime.InteropServices.RuntimeInformation .IsOSPlatform(OSPlatform.Windows)
Merci au commentaire d’Oleksii Vynnychenko
Vous pouvez obtenir le nom et la version du système d’exploitation sous forme de chaîne en utilisant
var osNameAndVersion = System.Runtime.InteropServices.RuntimeInformation.OSDescription
Par exemple, osNameAndVersion
serait Microsoft Windows 10.0.10586
System.Environment.OSVersion.Platform
peut être utilisé dans .NET Framework complet et Mono mais:
System.Runtime.InteropServices.RuntimeInformation
peut être utilisé dans .NET Core mais:
Vous pouvez appeler des fonctions non gérées spécifiques à la plate-forme telles que uname()
mais:
Donc, ma solution suggérée (voir code ci-dessous) peut sembler sournoise au début mais:
ssortingng windir = Environment.GetEnvironmentVariable("windir"); if (!ssortingng.IsNullOrEmpty(windir) && windir.Contains(@"\") && Directory.Exists(windir)) { _isWindows = true; } else if (File.Exists(@"/proc/sys/kernel/ostype")) { ssortingng osType = File.ReadAllText(@"/proc/sys/kernel/ostype"); if (osType.StartsWith("Linux", SsortingngComparison.OrdinalIgnoreCase)) { // Note: Android gets here too _isLinux = true; } else { throw new UnsupportedPlatformException(osType); } } else if (File.Exists(@"/System/Library/CoreServices/SystemVersion.plist")) { // Note: iOS gets here too _isMacOsX = true; } else { throw new UnsupportedPlatformException(); }