How to Load Config File Programmatically
Suppose I have a Custom Config File which corresponds to a Custom-defined ConfigurationSection and Config elements. These config classes are stored in a library.
Config File looks like this
<?xml version="1.0" encoding="utf-8" ?>
<Schoool Name="RT">
<Student></Student>
</Schoool>
How can I programmatically load and use this config file from Code?
I don't want to use raw XML handling, but leverage the config classes already defined.
You'll have to adapt it for your requirements, but here's the code I use in one of my projects to do just that:
var fileMap = new ConfigurationFileMap("pathtoconfigfile");
var configuration = ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
var sectionGroup = configuration.GetSectionGroup("applicationSettings"); // This is the section group name, change to your needs
var section = (ClientSettingsSection)sectionGroup.Sections.Get("MyTarget.Namespace.Properties.Settings"); // This is the section name, change to your needs
var setting = section.Settings.Get("SettingName"); // This is the setting name, change to your needs
return setting.Value.ValueXml.InnerText;
Note that I'm reading a valid .net config file. I'm using this code to read the config file of an EXE from a DLL. I'm not sure if this works with the example config file you gave in your question, but it should be a good start.
Check out Jon Rista's three-part series on .NET 2.0 configuration up on CodeProject.
- Unraveling the mysteries of .NET 2.0 configuration
- Decoding the mysteries of .NET 2.0 configuration
- Cracking the mysteries of .NET 2.0 configuration
Highly recommended, well written and extremely helpful!
You can't really load any XML fragment - what you can load is a complete, separate config file that looks and feels like app.config.
If you want to create and design your own custom configuration sections, you should definitely also check out the Configuration Section Designer on CodePlex - a Visual Studio addin that allows you to visually design the config sections and have all the necessary plumbing code generated for you.