macos 如何正确检测 Windows、Linux 和 Mac 操作系统
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10138040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect properly Windows, Linux & Mac operating systems
提问by virrea
I could not found anything really efficient to detect correctly what platform (Windows / Linux / Mac) my C# progrma was running on, especially on Mac which returns Unix and can't hardly be differenciated with Linux platforms !
我找不到任何真正有效的方法来正确检测我的 C# 程序在哪个平台(Windows / Linux / Mac)上运行,尤其是在返回 Unix 并且几乎无法与 Linux 平台区分的 Mac 上!
So I made something less theoretical, and more practical, based on specificities of Mac.
所以我根据 Mac 的特性做了一些不那么理论化、更实际的东西。
I'm posting the working code as an answer. Please, comment if it works well for you too / can be improved.
我正在发布工作代码作为答案。请评论它是否也适合您/可以改进。
Thanks !
谢谢 !
Response :
回复 :
Here is the working code !
这是工作代码!
public enum Platform
{
Windows,
Linux,
Mac
}
public static Platform RunningPlatform()
{
switch (Environment.OSVersion.Platform)
{
case PlatformID.Unix:
// Well, there are chances MacOSX is reported as Unix instead of MacOSX.
// Instead of platform check, we'll do a feature checks (Mac specific root folders)
if (Directory.Exists("/Applications")
& Directory.Exists("/System")
& Directory.Exists("/Users")
& Directory.Exists("/Volumes"))
return Platform.Mac;
else
return Platform.Linux;
case PlatformID.MacOSX:
return Platform.Mac;
default:
return Platform.Windows;
}
}
采纳答案by TheNextman
Maybe check out the IsRunningOnMacmethod in the Pinta source:
也许查看Pinta 源中的IsRunningOnMac方法:
回答by Stev
Per the remarks on the Environment.OSVersion Property page:
根据Environment.OSVersion 属性页面上的注释:
The Environment.OSVersion property does not provide a reliable way to identify the exact operating system and its version. Therefore, we do not recommend that you use this method. Instead: To identify the operating system platform, use the RuntimeInformation.IsOSPlatform method.
Environment.OSVersion 属性不提供一种可靠的方法来识别确切的操作系统及其版本。因此,我们不建议您使用此方法。相反:要识别操作系统平台,请使用 RuntimeInformation.IsOSPlatform 方法。
RuntimeInformation.IsOSPlatformworked for what I needed.
RuntimeInformation.IsOSPlatform为我所需要的工作。
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// Your OSX code here.
}
elseif (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
// Your Linux code here.
}