I find it easier to work with the Version
class:
using Microsoft.Win32;
using System.Runtime.InteropServices;
namespace System.Runtime.InteropServices {
public static class RuntimeInformationEx {
public static Version? GetDotnetFrameworkVersion() {
using var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full");
if (key is object) {
if (!Int32.TryParse(key.GetValue("Release", "").ToString(), out var release)) return null;
return release switch
{
378389 => new Version(4, 5, 0),
378675 => new Version(4, 5, 1),
378758 => new Version(4, 5, 1),
379893 => new Version(4, 5, 2),
393295 => new Version(4, 6, 0),
393297 => new Version(4, 6, 0),
394254 => new Version(4, 6, 1),
394271 => new Version(4, 6, 1),
394802 => new Version(4, 6, 2),
394806 => new Version(4, 6, 2),
460798 => new Version(4, 7, 0),
460805 => new Version(4, 7, 0),
461308 => new Version(4, 7, 1),
461310 => new Version(4, 7, 1),
461808 => new Version(4, 7, 2),
461814 => new Version(4, 7, 2),
528040 => new Version(4, 8, 0),
528209 => new Version(4, 8, 0),
528049 => new Version(4, 8, 0),
_ => null
};
} else { // .NET version < 4.5
using var key1 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP");
if (key1 is null) return null;
var parts = key1.GetSubKeyNames()[^1].Substring(1).Split('.'); // get lastsub key, remove 'v' prefix, and split
if (parts.Length == 2) parts = new string[] { parts[0], parts[1], "0" };
if (parts.Length != 3) return null;
Func<string, int> Parse = s => Int32.TryParse(s, out var i) ? i : -1;
try { return new Version(Parse(parts[0]), Parse(parts[1]), Parse(parts[2])); } catch { return null; }
}
}
public static Version? GetDotnetCoreVersion() {
if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Core ")) return null;
var parts = RuntimeInformation.FrameworkDescription.Substring(10).Split('.');
if (parts.Length == 2) parts = new string[] { parts[0], parts[1], "0" };
if (parts.Length != 3) return null;
Func<string, int> Parse = s => Int32.TryParse(s, out var i) ? i : -1;
try { return new Version(Parse(parts[0]), Parse(parts[1]), Parse(parts[2])); } catch { return null; }
}
}
}
(code is C#8)