The best way to get a path to machine.config of a different .NET version

*爱你&永不变心* 提交于 2019-12-07 17:59:25

Since I needed the path to machine.config for ASP.NET versions, I didn't care about all .NET framework paths (e.g. 3 and 3.5 frameworks since they are just extensions of 2.0). I ended up querying HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET registry key and Path value of the framework key. Finally appending config\machine.config to the framework path yielded desired results.

The method to map ASP.NET runtime to machine.config path would take strings of any format "v2.0", "2.0.50727.0" or just "v2" and "2", regex it to either one decimal digit like "2.0" or one first digit if decimal digits were not specified like "2" and get the right value from the registry. Something similar to this:


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");

Lastly, I pass this configs to WebConfigurationMap (I am using Microsoft.Web.Administration, but you can use it with System.Configuration as well, the code is almost the same):


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

WebConfigurationMap maps configuration to custom machine.config and root web.config (hence null as a second argument in GetWebConfiguration())

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!