问题
Whats the best way to get a path to .net 2.0 machine.config file, if the application is running on .net 4.0?
One way would be to do string manipulation and file system access to replace v4.0* with v2.0* in
new ConfigurationFileMap().MachineConfigFilename;
and then pass it to ConfigurationManager.OpenMappedMachineConfiguration(new ConfigurationFileMap(<HERE>))
. I will resort to this solution if nothing better is available.
回答1:
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())
来源:https://stackoverflow.com/questions/4514936/the-best-way-to-get-a-path-to-machine-config-of-a-different-net-version