OpenMappedExeConfiguration与OpenExeConfiguration

OpenExeConfiguration有2个重载:

  • ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel) —–(1)
  • ConfigurationManager.OpenExeConfiguration(String) —–(2)

OpenMappedExeConfiguration只有1个原型:

  • OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap,ConfigurationUserLevel userLevel) —–(3)

似乎(2)和(3)都可用于打开特定的配置文件而不是默认的app.config文件。

那么它们之间的区别是什么? 什么时候用哪个?

为什么我们在(1)和(2)中分隔UserLevelConfig File Location ,但是在(3)中将它们组合在一起?

谢谢你的回复。

更新

我知道微软总是喜欢以多种方式做事。 但它应该这样做是有原因的。 任何人都知道我的问题中的原因? 我们需要赏金吗?)?

最终的.NET配置资源 – 破解.NET 2.0配置之谜解释了这种差异:

OpenExeConfiguration(String)

将“.config”附加到您提供的文件名并加载该配置文件。 重要的是要注意OpenExeConfiguration(字符串exePath)是一个非常误导的方法,因为文件名不必是正在运行的.exe的文件名[…]通过提供EXE文件名以外的文件名,备用* .config文件可以打开。

OpenExeConfiguration(ConfigurationUserLevel)

第二种方法OpenExeConfiguration(ConfigurationUserLevel级别)将为指定的配置级别加载适当的配置文件。 Exe上下文中提供的配置级别允许您指定是否需要exe,漫游用户或本地用户配置[…]请记住,配置是分层的并且已合并。 请求漫游或本地用户配置时,将合并通过machine.config的级别,从而使应用程序可以访问给定用户级别的完整配置。

OpenMappedExeConfiguration(),OpenMappedMachineConfiguration()

与OpenExeConfiguration()方法不同,OpenExpedConfiguration()方法对配置文件所在的位置做了一些假设,OpenMappedExeConfiguration()和OpenMappedMachineConfiguration()允许您明确指定* .config文件在磁盘上的位置。 使用这些方法,您可以加载备用machine.config,从您自己选择的位置加载User.config文件(而不是让.NET框架决定一些复杂的路径)等。访问machine.config时,自定义不需要版本,应该使用OpenMachineConfiguration()。

OpenExeConfiguration (String)OpenMappedExeConfiguration (ExeConfigurationFileMap, ConfigurationUserLevel)之间的区别在于映射版本允许您使用ExeConfigurationFileMap选择要打开的配置文件。

如果您使用OpenExeConfiguration(string)重载,那么它将使用Machine和Exe配置位置打开配置,而映射版本将允许您从任何位置选择要加载的特定文件(显然仍然尊重权限等)。

如果您查看源代码,两种方法实际上都调用相同的实现方法:

 public static System.Configuration.Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap, ConfigurationUserLevel userLevel) { return OpenExeConfigurationImpl(fileMap, false, userLevel, null); } public static System.Configuration.Configuration OpenExeConfiguration(string exePath) { return OpenExeConfigurationImpl(null, false, ConfigurationUserLevel.None, exePath); } 

那么何时使用一个而不是另一个? 如果不想打开默认配置文件,请使用OpenMappedExeConfiguration 。 根据我的经验,我唯一一次调用这些方法之一的时候是想要读取非默认配置,所以我只使用了OpenMappedExeConfiguration