2010-12-23 60 views
1

如果應用程序在.net 4.0上運行,獲取.net 2.0 machine.config文件路徑的最佳方式是什麼?獲取不同.NET版本的machine.config路徑的最佳方式

一種方法是將字符串操作和文件系統訪問替換爲v2.0.0 *版本 new ConfigurationFileMap().MachineConfigFilename;,然後將其傳遞給ConfigurationManager.OpenMappedMachineConfiguration(new ConfigurationFileMap(<HERE>))。如果沒有更好的解決方案,我會採用這種解決方案。

回答

7

因爲我需要用於ASP.NET版本的machine.config的路徑,所以我不關心所有.NET框架路徑(例如3和3.5框架,因爲它們只是2.0的擴展)。我結束了查詢HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET註冊表項和框架密鑰的值Path。最後將config\machine.config附加到框架路徑產生期望的結果。

將ASP.NET運行時映射到machine.config路徑的方法將採用任何格式「v2.0」,「2.0.50727.0」或「v2」和「2」的任何格式的字符串,將其與十進制數如「2.0」或如果十進制數字未指定爲「2」並且從註冊表中獲取正確值,則爲一位數字。一些與此類似:


string runtimeVersion = "2.0"; 
string frameworkPath; 
RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\ASP.NET"); 
foreach (string childKeyName in regKey.GetSubKeyNames()) 
{ 
    if (Regex.IsMatch(childKeyName, runtimeVersion)) 
    { 
     RegistryKey subKey = regKey.OpenSubKey(childKeyName)) 
     { 
      frameworkPath = (string)subKey.GetValue("Path"); 
     } 
    } 
} 
string machineConfigPath = Path.Combine(frameworkPath, @"config\machine.config"); 
string webRootConfigPath = Path.Combine(frameworkPath, @"config\web.config"); 

最後,我通過這個CONFIGS到WebConfigurationMap(我使用Microsoft.Web.Administration,但你可以用System.Configuration使用它,以及,代碼幾乎是相同的):


using (ServerManager manager = new ServerManager()) 
{ 
    Configuration rootWebConfig = manager.GetWebConfiguration(new WebConfigurationMap(machineConfigPath, webRootConfigPath), null); 
} 

WebConfigurationMap映射配置定製的machine.config和根web.config(因此null作爲在GetWebConfiguration第二個參數())

相關問題