How to Read a custom config section from app.config in C#
By FoxLearn 3/20/2025 1:48:17 AM 48
You can achieve this by implementing IConfigurationSectionHandler
and using ConfigurationManager.GetSection()
.
1. Create a Custom Config Class
Start by defining a class that will hold the configuration values you want to store in app.config
. Here's an example of a simple DatabaseConfig
class:
public class DatabaseConfig { public string Server { get; set; } public string DatabaseName { get; set; } public bool IsIntegratedSecurity { get; set; } public int ConnectionTimeout { get; set; } }
2. Implement IConfigurationSectionHandler
to Load the Section
Next, implement IConfigurationSectionHandler.Create()
to load the custom section from the config file into an object:
- Use reflection to match the section name with the corresponding target type.
- Use
XmlSerializer
to deserialize the XML data of the section to the target class.
Here's the code for the custom configuration loader:
using System; using System.Configuration; using System.Linq; using System.Xml; using System.Xml.Serialization; public class DatabaseConfigLoader : IConfigurationSectionHandler { public object Create(object parent, object configContext, XmlNode section) { if (section == null) { throw new ArgumentNullException($"XMLNode passed in is null."); } var type = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(a => a.GetTypes()) .FirstOrDefault(t => t.Name == section.Name); if (type == null) { throw new ArgumentException($"Type with name {section.Name} couldn't be found."); } var serializer = new XmlSerializer(type, new XmlRootAttribute(section.Name)); using (XmlReader reader = new XmlNodeReader(section)) { return serializer.Deserialize(reader); } } }
Note that this solution works for any type, not just the DatabaseConfig
class we defined in Step 1.
3. Add the Custom Config Section to app.config
Now, add the custom section in the configSections
node of the app.config
file. You need to define a <section>
node that references the custom configuration loader.
For example, How to modify your app.config
:
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="DatabaseConfig" type="MyApp.DatabaseConfigLoader, MyApp" /> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> </startup> <DatabaseConfig> <Server>localhost</Server> <DatabaseName>MyDatabase</DatabaseName> <IsIntegratedSecurity>true</IsIntegratedSecurity> <ConnectionTimeout>30</ConnectionTimeout> </DatabaseConfig> </configuration>
Explaining the <section>
Node in app.config
The <section>
node tells the system to use the DatabaseConfigLoader
class to load the custom XML section. Here’s the breakdown:
<section name="DatabaseConfig" type="MyApp.DatabaseConfigLoader, MyApp" />
name
: The name of the custom XML node (i.e.,<DatabaseConfig>
).type
: The full class name, including the namespace and assembly, which implementsIConfigurationSectionHandler
.
If the name
or type
does not match, a ConfigurationErrorsException
will be thrown.
4. Use ConfigurationManager.GetSection()
Finally, you can load the custom configuration section using ConfigurationManager.GetSection()
.
static void Main(string[] args) { var config = (DatabaseConfig)ConfigurationManager.GetSection(nameof(DatabaseConfig)); Console.WriteLine($"Server: {config.Server}"); Console.WriteLine($"Database: {config.DatabaseName}"); Console.WriteLine($"Integrated Security: {config.IsIntegratedSecurity}"); Console.WriteLine($"Timeout: {config.ConnectionTimeout}"); }
This will output the following values, as defined in the app.config
:
Server: localhost Database: MyDatabase Integrated Security: True Timeout: 30
This method of reading custom configuration sections is powerful and flexible, allowing you to load complex configuration structures directly into your application.
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization