How to check the OS version at runtime, e.g. on Windows or Linux, without using a conditional compilation statement

后端 未结 7 1118
生来不讨喜
生来不讨喜 2020-11-28 08:57

How do I determine what platform my C# code is running on? for example whether it is running on Linux or windows so that I can execute different code at runtime.

I h

7条回答
  •  星月不相逢
    2020-11-28 09:43

    [Editor's Note: This answer was applicable before .NET 4.7.1, or before the Windows Compatibility Pack for .NET Core was released. The current best answer is Alex Sanséau's to Stack Overflow question How to check the OS version at runtime, e.g. on Windows or Linux, without using a conditional compilation statement.]

    You can detect the execution platform using System.Environment.OSVersion.Platform:

    public static bool IsLinux
    {
        get
        {
            int p = (int) Environment.OSVersion.Platform;
            return (p == 4) || (p == 6) || (p == 128);
        }
    }
    

    From the Mono FAQ:

    How to detect the execution platform

    The execution platform can be detected by using the System.Environment.OSVersion.Platform value. However correctly detecting Unix platforms, in every cases, requires a little more work. The first versions of the framework (1.0 and 1.1) didn't include any PlatformID value for Unix, so Mono used the value 128. The newer framework 2.0 added Unix to the PlatformID enum but, sadly, with a different value: 4 and newer versions of .NET distinguished between Unix and macOS, introducing yet another value 6 for macOS.

    This means that in order to detect properly code running on Unix platforms you must check the three values (4, 6 and 128). This ensure that the detection code will work as expected when executed on Mono CLR 1.x runtime and with both Mono and Microsoft CLR 2.x runtimes.

提交回复
热议问题