获取不同.NET版本的machine.config路径的最佳方法

如果应用程序在.net 4.0上运行,那么获取.net 2.0 machine.config文件路径的最佳方法是什么?

一种方法是进行字符串操作和文件系统访问,以便在new ConfigurationFileMap().MachineConfigFilename;中用v2.0 *替换v4.0 * new ConfigurationFileMap().MachineConfigFilename; 然后将其传递给ConfigurationManager.OpenMappedMachineConfiguration(new ConfigurationFileMap()) 。 如果没有更好的可用性,我将采用这种解决方案。

由于我需要为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"); 

最后,我将此配置传递给WebConfigurationMap(我使用的是Microsoft.Web.Administration,但您也可以将它与System.Configuration一起使用,代码几乎相同):

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

WebConfigurationMap将配置映射到自定义machine.config和root web.config(因此null作为GetWebConfiguration()中的第二个参数)