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

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

    One more option is to use Process to call a shell script to get the uname, as follows:

    Process p = new Process {
      StartInfo = {
        UseShellExecute        = false,
        RedirectStandardOutput = true,
        FileName               = "uname",
        Arguments              = "-s"
      }
    };
    p.Start();
    string uname = p.StandardOutput.ReadToEnd().Trim();
    
    if (uname == "Darwin") {
      // OS X
    } else {
      // ...
    }
    

提交回复
热议问题