t.oneill
t.oneill

Reputation: 37

Saving a list of objects to text file

Hello im trying to save a list of objects into a text file. Below is the code im using.

The problem im having is that instead of displaying a string for each item like:

"BMW|6 Series|2007|10900|17000|Convertible|Automatic|Petrol|".

It is displaying: "Car_Manager.Car" for each item in the list. Thanks for your help.

    private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        // Save everything in a dialog box
        saveFileDialog1.ShowDialog();
        // Open the file and save the information
        Stream textOut = saveFileDialog1.OpenFile();
        StreamWriter writer = new StreamWriter(textOut);

     foreach(Car c in cars)
        {

            writer.WriteLine(c);
        }
            writer.Close();

    }

Upvotes: 0

Views: 3617

Answers (3)

Iain Ward
Iain Ward

Reputation: 9936

You need to override the ToString() method or write a new method to write out each property value separately.

e.g.

public string ToDelimitedString()
{
    StringBuilder result = new StringBuilder();
    result.Append(String.Format("{0}|{1}|{2}", this.Make, this.Model, this.Year));
    return result.ToString();
}


foreach(Car c in cars)
{
    writer.WriteLine(c.ToDelimitedString());
}

By default objects are converted to strings via their ToString method, which returns the object type name as a default.

Out of interest, why are you writing them to a text file? Xml serialization is ideal for this sort of situation.

Upvotes: 1

Valeklosse
Valeklosse

Reputation: 1017

As an alternative you could use an extension method. Something similar to the below.

public static class CarExtensionMethods {
    public static string TextFileString(this Car car) {
        return string.format("{0}|{1}|{2}", car.Make, car.Model, car.Year);
    }
}

Then use as follows

var carString = car.TextFileString();

Upvotes: 0

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

You have to implement ToString-method:

class Car 
{
    public override string ToString() 
    {
        return this.Name;  // or whatever property you need for your car-models
    }
}

This provides a string-representation for every car in your list which is then used by WriteLine().

Alternativly instead of using WriteLine(c) you may simply use WriteLine(c.Name).

What you currently see ("Car_Manager.Car") is the default-implementation which is inherited by every class as it is implemented on the object-class. So you may simply override it whith the given statem,ents and you´re done.

Upvotes: 6

Related Questions