Retrieve the current Framework Directory

I needed the ablity to get the directory of the most current version of the framework on them machine, but there were no built in functions in the framework to do this (at least none that I could find). So I did a little hunting around and found where the framework installation path is stored in the registry and combined that with the Environment.Version to get the framework directory. Here is a sample function to retrieve the framework directory:

using System;
using Microsoft.Win32;

...
///  /// This method will retrieve the directory of the framework that this /// program is executing under.  It accomplishes this by getting the /// install root directory from the registry and then getting the framework /// version by using Environment.Version. ///  /// path of the framework executing this program public static string GetFrameworkDirectory() {   // This is the location of the .Net Framework Registry Key   string framworkRegPath = @"Software\Microsoft\.NetFramework";
  // Get a non-writable key from the registry   RegistryKey netFramework = Registry.LocalMachine.OpenSubKey(framworkRegPath, false);
  // Retrieve the install root path for the framework   string installRoot = netFramework.GetValue("InstallRoot").ToString();
  // Retrieve the version of the framework executing this program   string version = string.Format(@"v{0}.{1}.{2}\",     Environment.Version.Major,      Environment.Version.Minor,     Environment.Version.Build); 
  // Return the path of the framework   return System.IO.Path.Combine(installRoot, version);      }

3 Comments

  • Thanks for the information Jamie, this was the kind of thing I was trying to find. Although how does Assembly.GetAssembly locate the assembly? Through the GAC maybe? but then how does it know where the GAC is located? Does it ultimatly come down to looking at a registry key? This I don't know.





    What I do know is if I change the registry key noted in my sample code no .net programs will run. It complains that the framework is not installed.





    Wes


  • All Assembly.GetAssembly(type) seems to do is return type.Module.Assembly. I don't know why anyone would want to use this rather than type.Assembly.





    I think the mscorlib assembly is the only framework assembly that don't live in the GAC. The component that knows where the GAC is and how to access it Fucion (it's a native code COM component).

  • I just say:

    System.Web.HttpRuntime.ClrInstallDirectory

    This should work under all possible constructions.

Comments have been disabled for this content.