1、使用IsOSPlatform()和OSDescription判断
使用System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform()
判断平台操作系统,参数包括:
OSPlatform.Windows
OSPlatform.OSX
OSPlatform.Linux
例如,
bool isWindows = System.Runtime.InteropServices.RuntimeInformation
.IsOSPlatform(OSPlatform.Windows);
//使用OSDescription获取操作系统版本信息,如可能值为Microsoft Windows 10.0.10586
var osNameAndVersion = System.Runtime.InteropServices.RuntimeInformation.OSDescription;
2、通过系统环境变量判断
string windir = Environment.GetEnvironmentVariable("windir");
if (!string.IsNullOrEmpty(windir) && windir.Contains(@"\") && Directory.Exists(windir))
{
_isWindows = true;
}
else if (File.Exists(@"/proc/sys/kernel/ostype"))
{
string osType = File.ReadAllText(@"/proc/sys/kernel/ostype");
if (osType.StartsWith("Linux", StringComparison.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();
}