【发布时间】:2016-12-11 23:04:58
【问题描述】:
如何确定我的 .NET Core 应用在哪个操作系统上运行?
过去我可以使用Environment.OSVersion。
目前确定我的应用是在 Mac 还是 Windows 上运行的方法是什么?
【问题讨论】:
-
不是我想要的答案,而是我自己找到的。
如何确定我的 .NET Core 应用在哪个操作系统上运行?
过去我可以使用Environment.OSVersion。
目前确定我的应用是在 Mac 还是 Windows 上运行的方法是什么?
【问题讨论】:
System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform()
OSPlatform.Windows
OSPlatform.OSX
OSPlatform.Linux
bool isWindows = System.Runtime.InteropServices.RuntimeInformation
.IsOSPlatform(OSPlatform.Windows);
感谢 Oleksii Vynnychenko 的评论
您可以使用字符串获取操作系统名称和版本
var osNameAndVersion = System.Runtime.InteropServices.RuntimeInformation.OSDescription;
例如osNameAndVersion 将是 Microsoft Windows 10.0.10586
【讨论】:
System.Runtime.InteropServices.RuntimeInformation.OSDescription - 返回操作系统的描述以及版本等。
System.Environment.OSVersion.Platform 以保持一致性?
IsOSPlatform(OSPlatform.Create("FreeBSD")) 来探测其他操作系统是现在支持还是将来可能添加。但是,对于要传递哪些字符串的安全方法不是很清楚(例如,大小写是否重要,或者"bsd" 是否同时匹配"FreeBSD" 和"NetBSD"?)。请参阅有关此功能的讨论 here。
RuntimeInformation.IsOSPlatform 不查看当前操作系统,而是检查构建配置目标。证明:github.com/dotnet/runtime/blob/…检查这个答案stackoverflow.com/a/66618677/56621
System.Environment.OSVersion.Platform 可以在完整的 .NET Framework 和 Mono 中使用,但是:
System.Runtime.InteropServices.RuntimeInformation 可以在 .NET Core 中使用,但是:
您可以调用特定于平台的非托管函数,例如 uname(),但是:
所以我建议的解决方案(见下面的代码)一开始可能看起来很傻,但是:
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();
}
【讨论】:
检查System.OperatingSystem 类,它对每个操作系统都有静态方法,即 IsMacOS()、IsWindows()、IsIOS() 等。
【讨论】: