如何加载配置文件编程 [英] How to Load Config File Programmatically

查看:124
本文介绍了如何加载配置文件编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有对应于自定义配置节和配置元素的自定义配置文件。这些配置类存储在库中。

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.

配置文件看起来像这样

<?xml version="1.0" encoding="utf-8" ?>
<Schoool Name="RT">
  <Student></Student>
</Schoool>

如何编程方式加载并使用code这个配置文件?

How can I programmatically load and use this config file from Code?

我不希望使用原始XML处理,而是充分利用已定义的配置类。

I don't want to use raw XML handling, but leverage the config classes already defined.

推荐答案

你必须去适应它为您的要求,但这里的code我在我的项目之一,用它来做到这一点:

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;

请注意,我读一本有效的.NET配置文件。我使用这个code读取从DLL一个EXE的配置文件。我不知道这是否适用于你在你的问题给的例子配置文件,但它应该是一个良好的开端。

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.

这篇关于如何加载配置文件编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆