因爲我需要用於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第二個參數())