假设我有一个自定义配置文件,它对应于自定义的ConfigurationSection和Config元素.这些配置类存储在库中.
Config File看起来像这样
<?xml version="1.0" encoding="utf-8" ?>
<Schoool Name="RT">
<Student></Student>
</Schoool>
Run Code Online (Sandbox Code Playgroud)
如何以编程方式从代码中加载和使用此配置文件?
我不想使用原始XML处理,而是利用已经定义的配置类.
Mar*_*arc 17
你必须根据你的要求调整它,但这是我在我的一个项目中使用的代码:
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;
Run Code Online (Sandbox Code Playgroud)
请注意,我正在阅读有效的.net配置文件.我正在使用此代码从DLL中读取EXE的配置文件.我不确定这是否适用于您在问题中提供的示例配置文件,但它应该是一个良好的开端.
在CodeProject上查看Jon Rista关于.NET 2.0配置的三部分系列.
强烈推荐,写得很好,非常有帮助!
您无法真正加载任何XML片段 - 您可以加载的是一个完整,独立的配置文件,其外观和感觉就像是app.config.
如果您想创建和设计自己的自定义配置部分,您还应该查看CodePlex上的配置部分设计器 - 一个Visual Studio插件,它允许您直观地设计配置部分并为您生成所有必需的管道代码.
归档时间: |
|
查看次数: |
36350 次 |
最近记录: |