简体   繁体   English

App.config格式和.NET中的访问数据

[英]App.config format and accessing data in .NET

I'm new with editing app.config. 我是编辑app.config的新手。 I'd like to have this section in app.config: 我想在app.config中有此部分:

<name1>
    <name2>
        <name3 att="something1">value1</name3>
        <name3 att="something2">value2</name3>
        ...
    </name2>
</name1>

How to create it and access it from code? 如何创建它并从代码中访问它? I want to get something1 , something2 , value1 and value2 . 我想要得到something1something2value1value2 I found this tutorial , but it shows only how to get something1 , not something2 , value1 and value2 (Approach Four in tutorial). 我找到了本教程 ,但是它仅显示了如何获取something1 ,而不是something2value1value2 (教程中的方法四)。

Thank you for any help. 感谢您的任何帮助。

You'll need a custom configuration collection by subclassing ConfigurationElementCollection . 通过将ConfigurationElementCollection子类化,您将需要一个自定义配置集合。

Assuming <name1> is a immediate child of the root element you'll need: 假设<name1>是根元素的直接子元素,您将需要:

  • A custom section for <name1> <name1>自定义部分
  • It will need a custom collection for <name2> 它将需要<name2>的自定义集合
  • A custom element (to be a member of the collection) for each <name3> . 每个<name3>的自定义元素(将成为集合的成员)。

I solved it. 我解决了 First I needed to edit ConfigurationElement class for <name3> , I used the sample in this post . 首先,我需要编辑ConfigurationElement<name3>我用在这个样品 Then I needed to create class from ConfigurationElementCollection - so simpy coppied code for UrlsCollection class from the link and overwrited there all UrlConfigElement to my ConfigurationElement class. 然后,我需要从ConfigurationElementCollection创建类-因此从链接为UrlsCollection类简化复制代码, UrlsCollection将所有UrlConfigElement覆盖到我的ConfigurationElement类。

var section = ConfigurationManager.GetSection("name1") as Name1ConfigurationElement;
var collection = section.Name2;
foreach (SqlElement element in collection)
{
    Console.WriteLine(element.Value);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM