2008-12-17 188 views

回答

171

路徑到CLR活性當前.NET應用程序的安裝目錄可以通過使用以下方法來獲得:

System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() 

我會強烈反對直接讀取​​註冊表建議。例如,當.NET應用程序在64位系統中運行時,CLR可以從「C:\ Windows \ Microsoft.NET \ Framework64 \ v2.0.50727」(AnyCPU,x64編譯目標)或從「C:\ Windows \ Microsoft.NET \ Framework \ v2.0.50727「(x86編譯目標)。讀取註冊表將而不是告訴你哪兩個目錄中的哪一個被當前的CLR使用。

另一個重要的事實是,對於.NET 2.0,.NET 3.0和.NET 3.5應用程序,「當前CLR」將爲「2.0」。這意味着GetRuntimeDirectory()調用將返回2.0目錄,即使在.NET 3.5應用程序(從3.5目錄加載它們的某些程序集)內也是如此。根據您對術語「.NET Framework目錄路徑」的解釋,GetRuntimeDirectory可能不是您正在查找的信息(「CLR目錄」與「3.5程序集來自的目錄」)。

2

您可以從Windows註冊表抓住它:

using System; 
using Microsoft.Win32; 

// .. 。

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

Source

+11

我強烈建議不要直接訪問註冊表(在64位操作系統上這實際上可能會給出錯誤的答案)。詳情請參閱下面的答案。 – 2009-05-01 12:20:26

+1

同意@Milan - 絕對不推薦。 – 2010-12-09 12:12:53

+0

@CMS我想做像silvetlight版本一樣的。如果我是刪除註冊表鍵,這意味着軟件也從系統中卸載。謝謝 – 2015-01-29 12:33:10

-3
[HKLM] \軟件的

讀取值是\ Microsoft.NetFramework \ InstallRoot鍵 - 您將獲得「C:\ WINDOWS \ Microsoft.NET \ Framework」。然後追加所需的框架版本。

39

更簡單的方法是將組件包括Microsoft.Build.Utilities並使用

using Microsoft.Build.Utilities; 
ToolLocationHelper.GetPathToDotNetFramework(
     TargetDotNetFrameworkVersion.VersionLatest);