2010-12-23 59 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第二个参数())

相关问题