How do I detect what .NET Framework versions and service packs are installed?

后端 未结 13 2088
滥情空心
滥情空心 2020-11-22 01:31

A similar question was asked here, but it was specific to .NET 3.5. Specifically, I\'m looking for the following:

  1. What is the correct way to determine which .N
13条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 02:07

    The Framework 4 beta installs to a differing registry key.

    using System;
    using System.Collections.ObjectModel;
    using Microsoft.Win32;
    
    class Program
    {
        static void Main(string[] args)
        {
            foreach(Version ver in InstalledDotNetVersions())
                Console.WriteLine(ver);
    
            Console.ReadKey();
        }
    
    
        public static Collection InstalledDotNetVersions()
        {
            Collection versions = new Collection();
            RegistryKey NDPKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP");
            if (NDPKey != null)
            {
                string[] subkeys = NDPKey.GetSubKeyNames();
                foreach (string subkey in subkeys)
                {
                    GetDotNetVersion(NDPKey.OpenSubKey(subkey), subkey, versions);
                    GetDotNetVersion(NDPKey.OpenSubKey(subkey).OpenSubKey("Client"), subkey, versions);
                    GetDotNetVersion(NDPKey.OpenSubKey(subkey).OpenSubKey("Full"), subkey, versions);
                }
            }
            return versions;
        }
    
        private static void GetDotNetVersion(RegistryKey parentKey, string subVersionName, Collection versions)
        {
            if (parentKey != null)
            {
                string installed = Convert.ToString(parentKey.GetValue("Install"));
                if (installed == "1")
                {
                    string version = Convert.ToString(parentKey.GetValue("Version"));
                    if (string.IsNullOrEmpty(version))
                    {
                        if (subVersionName.StartsWith("v"))
                            version = subVersionName.Substring(1);
                        else
                            version = subVersionName;
                    }
    
                    Version ver = new Version(version);
    
                    if (!versions.Contains(ver))
                        versions.Add(ver);
                }
            }
        }
    }
    

提交回复
热议问题