From 39504ac64dbf0945b3e72b138e5303eefa7861f5 Mon Sep 17 00:00:00 2001 From: Matthew John Cheetham Date: Wed, 3 May 2023 13:21:51 -0700 Subject: [PATCH] platformutils: use .NET Environment.OSVersion on CoreCLR Since .NET 5 we can now use the `Environment.OSVersion` property to lookup the real OS version for macOS and Windows[1]. For .NET Framework (still used for our releases on Windows) we must continue to use the Win32 API `RtlGetVersion` to avoid any Windows compatibility nonsense. We continue to use `uname` on Linux. [1] https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/5.0/environment-osversion-returns-correct-version --- src/shared/Core/PlatformUtils.cs | 32 +++++++++++++------------------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/src/shared/Core/PlatformUtils.cs b/src/shared/Core/PlatformUtils.cs index d484d0227..b04dbe966 100644 --- a/src/shared/Core/PlatformUtils.cs +++ b/src/shared/Core/PlatformUtils.cs @@ -351,30 +351,24 @@ private static string GetOSType() private static string GetOSVersion(ITrace2 trace2) { + // + // Since .NET 5 we can use Environment.OSVersion because it was updated to + // return the correct version on Windows & macOS, rather than the manifested + // version for Windows or the kernel version for macOS. + // https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/5.0/environment-osversion-returns-correct-version + // + // However, we still need to use the old method for Windows on .NET Framework + // and call into the Win32 API to get the correct version (regardless of app + // compatibility settings). +#if NETFRAMEWORK if (IsWindows() && RtlGetVersionEx(out RTL_OSVERSIONINFOEX osvi) == 0) { return $"{osvi.dwMajorVersion}.{osvi.dwMinorVersion} (build {osvi.dwBuildNumber})"; } - - if (IsMacOS()) +#endif + if (IsWindows() || IsMacOS()) { - var psi = new ProcessStartInfo - { - FileName = "/usr/bin/sw_vers", - Arguments = "-productVersion", - RedirectStandardOutput = true - }; - - using (var swvers = new ChildProcess(trace2, psi)) - { - swvers.Start(Trace2ProcessClass.Other); - swvers.WaitForExit(); - - if (swvers.ExitCode == 0) - { - return swvers.StandardOutput.ReadToEnd().Trim(); - } - } + return Environment.OSVersion.VersionString; } if (IsLinux())