F. Parker
F. Parker

Reputation: 33

c# - How to save List of objects into a text file

I have a simple windows form application. Basically, I want to save the user's input of their ID number and name. I have a Person class:

class Person
{
    private string nric;
    private string name;

    public Person(string nric, string name)
    {
        this.nric = nric;
        this.name = name;
    }

And the .cs file:

    private void save_Click(object sender, EventArgs e)
    {
        List<Person> pList = new List<Person>();
        Person p1 = new Person(nric.Text, name.Text);
        pList.Add(p1);

        using (TextWriter tw = new StreamWriter("PersonFile.txt"))
        {
            foreach (Person p in pList)
            {
                tw.WriteLine(p);
            }
            tw.Close();
        }
    }

When I tried to run the codes, this is the output shown in the PersonFile.txt:

   Testing.Person

How do I make it such that the ID number and name would be displayed in the text file?

Upvotes: 0

Views: 12696

Answers (5)

MyHomieJR
MyHomieJR

Reputation: 75

You just print the Type of the Object.

Try this:

Tw.WriteLine($"Id: {p.nric}, Name: {p.name}");

Upvotes: 0

igorc
igorc

Reputation: 2034

override the toString() for the class

class Person
{
    private string nric;
    private string name;

    public override string ToString()
    {
       return name + " " + nric;
    }
}

then (no need to create StreamWriter):

File.WriteAllLines("PersonFile.txt", pList);

Upvotes: 0

reboris
reboris

Reputation: 9

You can add function to Person class

public string getPerson()
{
    return this.nric + " "+ thisname;
}

and change

tw.WriteLine(p);

to

call tw.WriteLine(p.getPerson());

Upvotes: 0

Miguel Costa
Miguel Costa

Reputation: 148

Add "ToString" method.

class Person
{
    private string nric;
    private string name;

    public Person(string nric, string name)
    {
        this.nric = nric;
        this.name = name;
    }

    public override string ToString()
    {
       return $"{nric} {name}";
    }
}

Upvotes: 8

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43936

The line

 tw.WriteLine(p);

simply calls p.ToString() and writes the returning string into your file. The default implementation of ToString() returns the name of the object's type.

One way to solve your issue is to overwrite ToString():

class Person
{
    private string nric;
    private string name;

    public Person(string nric, string name)
    {
        this.nric = nric;
        this.name = name;
    }

    public override string ToString()
    {
        return $"{nric} {name}";
    }
}

If you actually want to save the list in a way you can later load it again, you may want to read about serialization. There are easy ways to store and load objects in different formats (like xml, binary etc).

Upvotes: 1

Related Questions