Problem:
The .NET ConfigurationManager class is typically used for assembly configuration files. How can you load and utilize a separate, independent configuration file?
Solution:
While ConfigurationManager.OpenExeConfiguration()
targets assembly-specific config files, you can leverage OpenMappedExeConfiguration()
to load custom configuration files. Here's how:
ExeConfigurationFileMap
object:<code class="language-csharp">ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();</code>
ExeConfigFilename
property to the complete path of your custom configuration file. Note that the file extension is flexible:<code class="language-csharp">configMap.ExeConfigFilename = @"d:\test\justAConfigFile.config.whateverYouLikeExtension";</code>
ConfigurationManager.OpenMappedExeConfiguration()
to open the specified file:<code class="language-csharp">Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);</code>
<code class="language-csharp">config.AppSettings.Settings["test"].Value;</code>
Remember, the file extension you use for your custom configuration file is arbitrary.
The above is the detailed content of Can .NET's ConfigurationManager Load Non-Assembly-Related Config Files?. For more information, please follow other related articles on the PHP Chinese website!