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);
}
Read value of the [HKLM]\Software\Microsoft.NetFramework\InstallRoot key - you will get "C:\WINDOWS\Microsoft.NET\Framework". Then append with desired framework version.
I would strongly advice against reading the registry directly. For example, when a .NET application is running in 64bit systems, the CLR can either be loaded from "C:\Windows\Microsoft.NET\Framework64\v2.0.50727" (AnyCPU, x64 compilation targets) or from "C:\Windows\Microsoft.NET\Framework\v2.0.50727" (x86 compilation target). Reading registry will not tell you which one of the two directories was used by the current CLR.
Another important fact is that "the current CLR" will be "2.0" for .NET 2.0, .NET 3.0 and .NET 3.5 applications. This means that the GetRuntimeDirectory() call will return 2.0 directory even within .NET 3.5 applications (that load some of their assemblies from 3.5 directory). Depending on your interpretation of the term ".NET Framework directory path", GetRuntimeDirectory might not be the information you are looking for ("CLR directory" versus "directory from which 3.5 assemblies are coming from").
internal static class DotNetFrameworkLocator
{
public static string GetInstallationLocation()
{
const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";
using (var ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
{
if (ndpKey == null)
throw new Exception();
var value = ndpKey.GetValue("InstallPath") as string;
if (value != null)
return value;
else
throw new Exception();
}
}
}