如何正确检测Windows,Linux和Mac操作系统

vir*_*rea 19 c# macos mono cross-platform

我找不到任何真正有效的方法来正确检测我的C#progrma运行的平台(Windows/Linux/Mac),特别是在返回Unix的Mac上,并且几乎不能与Linux平台区别开来!

因此,基于Mac的特性,我做了一些不太理论化,更实用的东西.

我发布了工作代码作为答案.请评论它是否适合您/可以改进.

谢谢 !

回应:

这是工作代码!

    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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

小智 9

根据Environment.OSVersion 属性页面上的注释:

Environment.OSVersion 属性不提供可靠的方法来识别确切的操作系统及其版本。因此,我们不建议您使用此方法。相反:要识别操作系统平台,请使用 RuntimeInformation.IsOSPlatform 方法。

RuntimeInformation.IsOSPlatform满足我的需要。

if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
    // Your OSX code here.
}
elseif (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
    // Your Linux code here.
}
Run Code Online (Sandbox Code Playgroud)


The*_*man 7

也许看看Pinta源中的IsRunningOnMac方法: