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

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

    There isn't any such method, but you can use this method that checks it conditionally:

        public static OSPlatform GetOperatingSystem()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                return OSPlatform.OSX;
            }
    
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                return OSPlatform.Linux;
            }
    
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                return OSPlatform.Windows;
            }
    
            throw new Exception("Cannot determine operating system!");
        }
    
    0 讨论(0)
提交回复
热议问题