如何确定我的.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
,它返回关于操作系统的描述和版本等信息。 - Oleksii VynnychenkoSystem.Environment.OSVersion.Platform
呢? - leppieIsOSPlatform(OSPlatform.Create("FreeBSD"))
探测其他操作系统,无论它们现在是否受支持或将来可能添加。然而,关于传递什么字符串的安全方法不是很清楚(例如,大小写是否敏感,或者 "bsd"
是否匹配 "FreeBSD"
和 "NetBSD"
?)。请参见有关此功能的讨论此处。 - NightOwl888RuntimeInformation.IsOSPlatform
不是检查当前操作系统,而是检查构建配置目标。证据:https://github.com/dotnet/runtime/blob/57bfe474518ab5b7cfe6bf7424a79ce3af9d6657/src/libraries/System.Private.CoreLib/src/System/OperatingSystem.cs#L91请参考此答案 https://dev59.com/aVkT5IYBdhLWcg3wStzQ#66618677 - Alex from Jitbit查看 System.OperatingSystem
类,它拥有每个 OS 的静态方法,例如 IsMacOS()
、IsWindows()
、IsIOS()
等等。这些方法从 .NET 5 开始可用。
这使其成为一个不错的选择,因为这些方法的实现使用预处理指令,在编译时将返回值修正为针对每个目标操作系统的常量 true/false。没有运行时探测或调用。
以下是 OperatingSystem
中一个这样的方法的摘录:
/// <summary>
/// Indicates whether the current application is running on Linux.
/// </summary>
[NonVersionable]
public static bool IsLinux() =>
#if TARGET_LINUX && !TARGET_ANDROID
true;
#else
false;
#endif
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();
}
Environment.OSVersion
在 .NET Core 2.0+ 中可用。 - undefined