Effectively determine .NET Framework version
Verifying .NET Framework versions, especially 3.5 SP 1, is a common requirement for developers. However, just using Environment.Version()
to get this information only gets you the base version, leaving out important details like service packs.
To do this, several methods exist:
For .NET 1-4
A simple and effective method is to retrieve data directly from the registry. For .NET versions 1 to 4, you can use the following code snippet:
<code class="language-csharp">RegistryKey installed_versions = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP"); string[] version_names = installed_versions.GetSubKeyNames(); // version names 以 'v' 开头,例如 'v3.5',在转换前需要去除 double Framework = Convert.ToDouble(version_names[version_names.Length - 1].Remove(0, 1), CultureInfo.InvariantCulture); int SP = Convert.ToInt32(installed_versions.OpenSubKey(version_names[version_names.Length - 1]).GetValue("SP", 0));</code>
In this code, the "Framework" variable represents the highest installed version and "SP" holds the associated service pack number.
For .NET 4.5
For versions 4.5 and above, the official Microsoft documentation recommends the following method:
<code class="language-csharp">using System; using Microsoft.Win32; ... private static void Get45or451FromRegistry() { using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\")) { int releaseKey = Convert.ToInt32(ndpKey.GetValue("Release")); if (true) { Console.WriteLine("Version: " + CheckFor45DotVersion(releaseKey)); } } } ... // 使用 >= 检查版本将启用前向兼容性, // 但是您应该始终在新版本的框架上编译代码,以确保您的应用程序以相同的方式工作。 private static string CheckFor45DotVersion(int releaseKey) { if (releaseKey >= 528040) { return "4.8 或更高版本"; } if (releaseKey >= 461808) { return "4.7.2 或更高版本"; } if (releaseKey >= 461308) { return "4.7.1 或更高版本"; } if (releaseKey >= 460798) { return "4.7 或更高版本"; } if (releaseKey >= 394802) { return "4.6.2 或更高版本"; } if (releaseKey >= 394254) { return "4.6.1 或更高版本"; } if (releaseKey >= 393295) { return "4.6 或更高版本"; } if (releaseKey >= 393273) { return "4.6 RC 或更高版本"; } if ((releaseKey >= 379893)) { return "4.5.2 或更高版本"; } if ((releaseKey >= 378675)) { return "4.5.1 或更高版本"; } if ((releaseKey >= 378389)) { return "4.5 或更高版本"; } // 此行不应该执行。非空 release 密钥应该意味着 // 已安装 4.5 或更高版本。 return "未检测到 4.5 或更高版本"; }</code>
This code utilizes the registry to determine the installed .NET Framework version and its corresponding service pack.
Using these technologies, developers can quickly and accurately determine the installed .NET Framework version, allowing them to make informed decisions and ensure compatibility with their applications.
The above is the detailed content of How Can I Effectively Determine the Installed .NET Framework Version and Service Pack?. For more information, please follow other related articles on the PHP Chinese website!