【问题标题】:Custom app.config sections C#自定义 app.config 部分 C#
【发布时间】:2012-10-28 12:22:40
【问题描述】:

我在使用 app.config 时有点迷茫……我一直在使用 .ini 文件,但现在我想更改……这就是我的 .ini 文件的样子

[Clients]
1 = Client1
2 = Client 2
[Client1]
Employees = 4
1 = Employee1
2 = Employee2
3 = Employee3
4 = Employee4
[Client2]
Employees = 3
1 = Employee1
2 = Employee2
3 = Employee3

然后我使用了一些 for 循环,首先我搜索 [Clients],在那个 For client 中,我搜索它有多少员工,然后,我为每个员工做事......

我怎样才能把这个 .ini 转换成这样的东西

<Clients>
 <name = "client1">
  <Employees>
    <name = "employee1" />
    <name = "employee2" />
    <name = "employee3" />
    <name = "employee4" />
  </Employees>
 <name = "client2">
  <Employees>
    <name = "employee1" />
    <name = "employee2" />
    <name = "employee3" />
  </Employees>
</Clients>

然后使用该 app.config 执行循环操作

感谢您的建议。

更新 我试过这个 linq to xml 代码

XDocument doc = new XDocument(
         new XDeclaration("1.0", "utf-8", "yes"),
         new XComment("Configuración Checkcenter"),
         new XElement("Entidad",
             new XAttribute("nombre",cmbEntidad.Text),
             new XElement("Servicios",
                 new XElement("nombre", cmbServicio.Text))));

    doc.Save("settings.xml");

它有效,返回给我这个:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--My Settings-->
<Client name="Client1">
  <Employees>
    <name>Employee1</name>
  </Employees>
</Entidad>

但它总是在员工中替换我的名字......如果它不存在,我该如何处理它以添加新项目?我的意思是,如果新项目不存在,则为客户添加新项目。

【问题讨论】:

  • 看起来应该在数据库中,而不是配置文件中。也就是说,如果您必须使用文件,只需将其设为普通的 xml 文件(尝试使用 app.config 只会使事情变得不必要地复杂化).. 因此只需使用普通的 xml 类 / linq to xml(更新 - 请参阅 Preyash 的答案)

标签: c# wpf configuration settings


【解决方案1】:

正如其他人所说,这样的数据应该在易于使用的存储(即 DB、XML)上 但是,如果您必须为此使用 app.config 文件。 您必须查看 System.Configuration.Configuration 部分。

MSDN Link

关注 ConfigurationSection、ConfigurationElement 和 ConfigurationElementCollection 类。

【讨论】:

    【解决方案2】:

    为什么要使用 app.config? App.config 顾名思义应该用于存储配置设置。

    最好的办法是使用 Xml 文档。这将使您的数据与配置设置分开。从 XML 文件读取后,您可以使用 Linq to XML 查询这些数据。

    【讨论】:

      猜你喜欢
      • 2012-10-04
      • 1970-01-01
      • 2011-01-30
      • 2011-10-02
      • 2015-07-05
      • 2011-05-25
      • 2010-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多