有没有一种简单的方法来检查.NET Framework版本?方法来、版本、简单、NET

2023-09-02 21:08:04 作者:厚颜无耻滴家伙。

现在的问题是,我需要知道,如果它的3.5版本SP 1 Environment.Version()只返回 2.0.50727.3053

The problem is that I need to know if it's version 3.5 SP 1. Environment.Version() only returns 2.0.50727.3053.

我发现这个解决方案的,但我认为它会采取更多时间比它的价值,所以我在寻找一个简单的办法。这可能吗?

I found this solution, but I think it will take much more time than it's worth, so I'm looking for a simpler one. Is it possible?

推荐答案

像这样的东西应该这样做。刚刚从注册表中攫取价值

Something like this should do it. Just grab the value from the registry

对于.NET 1-4

框架是最高的已安装的版本, SP 的service pack,对于该版本。

Framework is the highest installed version, SP is the service pack for that version.

RegistryKey installed_versions = Registry.LocalMachine.OpenSubKey(@"SOFTWAREMicrosoftNET Framework SetupNDP");
string[] version_names = installed_versions.GetSubKeyNames();
//version names start with 'v', eg, 'v3.5' which needs to be trimmed off before conversion
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));

对于.NET 4.5 + (从官方文档):

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));
        }
    }
}


...


// Checking the version using >= will enable forward compatibility,  
// however you should always compile your code on newer versions of 
// the framework to ensure your app works the same. 
private static string CheckFor45DotVersion(int releaseKey)
{
    if (releaseKey >= 393273) {
       return "4.6 RC or later";
    }
    if ((releaseKey >= 379893)) {
        return "4.5.2 or later";
    }
    if ((releaseKey >= 378675)) {
        return "4.5.1 or later";
    }
    if ((releaseKey >= 378389)) {
        return "4.5 or later";
    }
    // This line should never execute. A non-null release key should mean 
    // that 4.5 or later is installed. 
    return "No 4.5 or later version detected";
}