Home > Backend Development > C++ > Can .NET's ConfigurationManager Load Non-Assembly-Related Config Files?

Can .NET's ConfigurationManager Load Non-Assembly-Related Config Files?

Linda Hamilton
Release: 2025-01-10 13:07:42
Original
194 people have browsed it

Can .NET's ConfigurationManager Load Non-Assembly-Related Config Files?

Loading Custom Configuration Files in .NET

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:

  1. Create a Configuration File Map: Instantiate an ExeConfigurationFileMap object:
<code class="language-csharp">ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();</code>
Copy after login
  1. Specify the Custom File Path: Set the 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>
Copy after login
  1. Open the Configuration File: Use ConfigurationManager.OpenMappedExeConfiguration() to open the specified file:
<code class="language-csharp">Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);</code>
Copy after login
  1. Access Configuration Values: Retrieve values from your configuration file using the indexer:
<code class="language-csharp">config.AppSettings.Settings["test"].Value;</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template