darko
darko

Reputation: 793

List to text file

I have a list of objects that holds groups of person. Each person has firstname, lastname, address and phone number.

I want to export that list into a text file looks like:

groupA
Firstname-david
LastName-kantor
Addres-italy
PhoneNumber-123456

What should I do? So far I managed to export only the object type names:

public List<PhoneBookCore> elements = new List<PhoneBookCore>();

string[] lines = elements.Select(phoneBookCore =>
    phoneBookCore.ToString()).ToArray();
System.IO.File.WriteAllLines(path, lines);

Upvotes: 0

Views: 4775

Answers (1)

C&#233;dric Bignon
C&#233;dric Bignon

Reputation: 13022

You have only the object type name because PhoneBookCore.ToString() gives you the object type name.

You have to specify how you want your file to look like. As MikeCorcoran a good way to do this is to use serialization. It is a very powerful way to store and retrieve data to/from file.

List<string> lines = new List<string>();
foreach(var phoneBookCore in elements)
{
    lines.Add(phoneBookCore.GroupName);  // Adds the Group Name
    foreach(var person in phoneBookCore.Persons)
    {
        // Adds the information on the person
        lines.Add(String.Format("FirstName-{0}", person.FirstName));
        lines.Add(String.Format("LastName-{0}", person.LastName));
        lines.Add(String.Format("Address-{0}", person.Address));
        lines.Add(String.Format("PhoneNumber-{0}", person.PhoneNumber));
    }
}
System.IO.File.WriteAllLines(path,lines);

Upvotes: 4

Related Questions