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

后端 未结 7 1102
生来不讨喜
生来不讨喜 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:29

    I found this recommendation on one of Microsoft's blogs:

    We recommend you to use RuntimeInformation.IsOSPlatform() for platform checks.

    Reference: Announcing the Windows Compatibility Pack for .NET Core

    IsOSPlatform() takes an argument of types OSPlatform which has three values by default: Windows, Linux and OSX. It can be used as follow:

    if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
    {
      // Do something
    }
    

    The API is part of .NET Standard 2.0, and therefore available in .NET Core 2.0 and .NET Framework 4.7.1.

提交回复
热议问题