以文本方式查看主题

-  中文XML论坛 - 专业的XML技术讨论区  (http://bbs.xml.org.cn/index.asp)
--  『 Dot NET,C#,ASP,VB 』  (http://bbs.xml.org.cn/list.asp?boardid=43)
----  C# code to detect which version of the .NET Framework is installed  (http://bbs.xml.org.cn/dispbbs.asp?boardid=43&rootid=&id=85221)


--  作者:卷积内核
--  发布时间:6/8/2010 11:24:00 AM

--  C# code to detect which version of the .NET Framework is installed
After searching on google for a simple method to get the current installed version of the .NET Framework, I decided to implement my own. I have put this method in its own class, because there are probably a lot of other similar methods that could be grouped together.

using System;
using System.IO;
using System.Security;
using System.Text.RegularExpressions;

namespace YourNameSpace
{
    public class SystemInfo
    {
        private const string FRAMEWORK_PATH = "\\Microsoft.NET\\Framework";
        private const string WINDIR1 = "windir";
        private const string WINDIR2 = "SystemRoot";

        public static string FrameworkVersion
        {
            get
            {
                try
                {
                    return getHighestVersion(NetFrameworkInstallationPath);
                }
                catch (SecurityException)
                {
                    return "Unknown";
                }
            }
        }

        private static string getHighestVersion(string installationPath)
        {
            string[] versions = Directory.GetDirectories(installationPath, "v*");
            string version = "Unknown";

            for (int i = versions.Length - 1; i >= 0; i--)
            {
                version = extractVersion(versions[i]);
                if (isNumber(version))
                    return version;
            }

            return version;
        }

        private static string extractVersion(string directory)
        {
            int startIndex = directory.LastIndexOf("\\") + 2;
            return directory.Substring(startIndex, directory.Length - startIndex);
        }

        private static bool isNumber(string str)
        {
            return new Regex(@"^[0-9]+\.?[0-9]*$").IsMatch(str);
        }

        public static string NetFrameworkInstallationPath
        {
            get { return WindowsPath + FRAMEWORK_PATH; }
        }

        public static string WindowsPath
        {
            get
            {
                string winDir = Environment.GetEnvironmentVariable(WINDIR1);
                if (String.IsNullOrEmpty(winDir))
                    winDir = Environment.GetEnvironmentVariable(WINDIR2);

                return winDir;
            }
        }
    }
}How it works? It searches the .NET Framework installation folder and returns the highest version installed on the system based on the folder names. I think the code is straightforward. I’d like to know other people’s thoughts and ideas. I know about other ways (registry keys, etc). I also hope this code helps other people to save some time.


--  作者:卷积内核
--  发布时间:6/8/2010 11:25:00 AM

--  
There was a question that surfaced on the Arizona .NET User Group list about determining which versions of .NET are on a system, and which service packs have been applied.  It sounded like a fun challenge, so I spent a few minutes this afternoon learning about how to dig up that data.  Definitely the most helpful information came from this post in Aaron Stebner's blog, which was pointed out by my friend Tim Heuer.  Aaron's sample code is only available in native C++ and VB.NET, so I decided to write a simplified version in C#.  Here is the pertinent code to dig up that information from the registry, which will work for anything that has “.NET Framework“ in its name:

// (Note that lbInstVersions is a listbox placed on a WinForm or Web Form.)
string componentsKeyName="SOFTWARE\\Microsoft\\Active Setup\\Installed Components",
   friendlyName,
   version;
// Find out in the registry anything under:
//    HKLM\SOFTWARE\Microsoft\Active Setup\Installed Components
// that has ".NET Framework" in the name
RegistryKey componentsKey=Registry.LocalMachine.OpenSubKey(componentsKeyName);
string[] instComps=componentsKey.GetSubKeyNames();
foreach(string instComp in instComps)
{
   RegistryKey key=componentsKey.OpenSubKey(instComp);
   friendlyName=(string)key.GetValue(null); // Gets the (Default) value from this key
   if(friendlyName != null && friendlyName.IndexOf(".NET Framework")>=0)
   {
      // Let's try to get any version information that's available
      version=(string)key.GetValue("Version");
      // If you want only the framework info with its SP level and not the
      // other hotfix and service pack detail, uncomment this if:
      //    if(version!=null && version.Split(',').Length>=4)
      lbInstVersions.Items.Add(friendlyName+(version!=null?(" ("+version+")"):""));
   }
}

It should work on a Win32 or Win64 system to detect versions of the framework installed either as an OCX or from an MSI.  So far (and hopefully this will always be), only true versions of the .NET Framework show up with this filter.

The commented out IF statement in the code above (next to the last line) just tests how many pieces come back from the version number when you Split() on a comma.  If it's four or more, it assumes it's not a hotfix or service pack, and thus it's a true framework installation.  The fourth number in the version number is in fact always the current service pack level.

From here it would be easy to make a class to describe framework versions, with major and minor numbers.  Also from there an IComparer so it's sortable in an array or SortedList.  The sky's the limit.  But really something like this becomes useful before installation of a product, so a VBScript version would be handy.  Maybe I'll write one of those next if anyone would find it useful.


--  作者:卷积内核
--  发布时间:6/8/2010 11:26:00 AM

--  
I found this while searching Google on how to determine the latest installed version of the .NET Framework. I added some custom code to compare the strings to determine which was greater. I wanted to share some code on how to determine the install directory of the latest version of the .NET Framework:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
class Program
{
[DllImport("mscoree.dll")]
private static extern int GetCORSystemDirectory(
[MarshalAs(UnmanagedType.LPWStr)]StringBuilder pbuffer,
int cchBuffer, ref int dwlength);

static void Main(string[] args)
{
GetClrInstallationDirectory();
}

private static void GetClrInstallationDirectory()
{
int MAX_PATH = 260;
StringBuilder sb = new StringBuilder(MAX_PATH);
GetCORSystemDirectory(sb, MAX_PATH, ref MAX_PATH);
Console.WriteLine(sb.ToString());
while(Console.Read() != 'q') ;
}

}
}


W 3 C h i n a ( since 2003 ) 旗 下 站 点
苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》
93.750ms