如何确定运行我的.NET Core应用程序的操作系统?过去我可以使用Environment.OSVersion
.
确定我的应用程序是在Mac还是Windows上运行的当前方法是什么?
dkn*_*ack 152
System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform()
Run Code Online (Sandbox Code Playgroud)
OSPlatform.Windows
OSPlatform.OSX
OSPlatform.Linux
Run Code Online (Sandbox Code Playgroud)
bool isWindows = System.Runtime.InteropServices.RuntimeInformation
.IsOSPlatform(OSPlatform.Windows);
Run Code Online (Sandbox Code Playgroud)
感谢Oleksii Vynnychenko的评论
您可以使用操作系统名称和版本作为字符串
var osNameAndVersion = System.Runtime.InteropServices.RuntimeInformation.OSDescription;
Run Code Online (Sandbox Code Playgroud)
例如,osNameAndVersion
将Microsoft Windows 10.0.10586
jar*_*riq 33
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();
}
Run Code Online (Sandbox Code Playgroud)
检查System.OperatingSystem
类,它具有针对每个操作系统的静态方法,即 IsMacOS()、IsWindows()、IsIOS() 等。
归档时间: |
|
查看次数: |
36331 次 |
最近记录: |