因为我需要用于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第二个参数())