简体   繁体   中英

Custom app.config sections C#

I'm a bit lost on using app.config... I've been using .ini files all the time but now I want to change... This is how my .ini looks

[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

Then I was using some for loops, first I search [Clients], inside that For client, I search how many employees does it have, and then, For each employee I do things...

How can I convert this .ini into something like this

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

And then do things with loops using that app.config

Thanks in advice.

UPDATE I've tried this linq to xml code

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");

It works, returns me this:

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

But it always replace my name in employees... How can I handle it to add new item if it doesn't exists? I mean, add new item to Employees for a client if it doesn't exist.

Why do you want to use app.config? App.config as the name suggest should be used to store configuration settings.

Best thing to do is to use an Xml document. This will keep your data separate from configuration settings. You can use Linq to XML to query these data once you read from XML file.

As the others have said, data like this should be on an easy to consume storage (ie DB, XML) But, if you must use the app.config file for this. You would have to look at the System.Configuration.Configurationsection.

MSDN Link

Focus on the ConfigurationSection, ConfigurationElement and ConfigurationElementCollection classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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