[英]Determine Operating System in .NET Core
How can I determine which operating system my .NET Core app is running on?如何确定我的 .NET Core 应用程序在哪个操作系统上运行? In the past I could use Environment.OSVersion
.过去我可以使用Environment.OSVersion
。
What is the current way to determine whether my app is running on Mac or Windows?当前确定我的应用程序是在 Mac 还是 Windows 上运行的方法是什么?
System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform()
OSPlatform.Windows
OSPlatform.OSX
OSPlatform.Linux
bool isWindows = System.Runtime.InteropServices.RuntimeInformation
.IsOSPlatform(OSPlatform.Windows);
Thanks to the comment by Oleksii Vynnychenko感谢 Oleksii Vynnychenko 的评论
You can get the operating systems name and version as a string using您可以使用字符串获取操作系统名称和版本
var osNameAndVersion = System.Runtime.InteropServices.RuntimeInformation.OSDescription;
Eg osNameAndVersion
would be Microsoft Windows 10.0.10586
例如osNameAndVersion
将是Microsoft Windows 10.0.10586
System.Environment.OSVersion.Platform
can be used in full .NET Framework and Mono but: System.Environment.OSVersion.Platform
可以在完整的 .NET Framework 和 Mono 中使用,但是:
System.Runtime.InteropServices.RuntimeInformation
can be used in .NET Core but: System.Runtime.InteropServices.RuntimeInformation
可以在 .NET Core 中使用,但是:
You could pinvoke platform specific unmanaged functions such as uname()
but:您可以调用特定于平台的非托管函数,例如uname()
但是:
So my suggested solution (see code bellow) may look sily at first but:所以我建议的解决方案(见下面的代码)一开始可能看起来很傻,但是:
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();
}
Check System.OperatingSystem
class it has static methods for each OS ie IsMacOS()
, IsWindows()
, IsIOS()
and so on.检查System.OperatingSystem
类,它具有每个操作系统的静态方法,即IsMacOS()
、 IsWindows()
、 IsIOS()
等。 These methods are available starting with .NET 5.这些方法从 .NET 5 开始可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.