Armistice
Armistice

Reputation: 5

How do I use Streamwriter to write my code on a new line

Hi I need to create a list in .txt but using these codes I am only able to write data and keying anymore will just overwrite the first one

        int score = Convert.ToInt32(ScoreLBL.Text);
        String name = NameTB.Text;
        List<Leaderboard> LB = new List<Leaderboard>();
        Leaderboard results;

        results = new Leaderboard(name, score);
        LB.Add(results);


        StreamWriter sw = new StreamWriter(@"C:\Users\zxong\Desktop\EGL138-OBJECT-ORIENTED PROGRAMMING\Project\Leaderboard.txt");
        for (int i = 0; i< LB.Count(); i++)
        {
            sw.WriteLine(LB[i].getName() + "," + LB[i].getScore());                
        }

Leaderboard class

    class Leaderboard
    {
    private String name;
    protected int score;

    public Leaderboard(String n, int s)
    {
        this.name = n;
        this.score = s;
    }

    public String getName()
    {
        return this.name;
    }

    public int getScore()
    {
        return this.score;
    }
}

Upvotes: 0

Views: 778

Answers (1)

Armando Bracho
Armando Bracho

Reputation: 729

i think this small change should be able to give you the functionality you want:

List<Leaderboard> LB = new List<Leaderboard>();

LB.Add(new Leaderboard("SomeName", 10));
LB.Add(new Leaderboard("AnotherName", 20));
LB.Add(new Leaderboard("ThirdName", 30));

using (StreamWriter sw = new StreamWriter(@"C:\Users\zxong\Desktop\EGL138-OBJECT-ORIENTED PROGRAMMING\Project\Leaderboard.txt", true)) {
   for (int i = 0; i < LB.Count; i++) {
      //Console.WriteLine(LB[i].getName() + "," + LB[i].getScore());
      sw.WriteLine(LB[i].getName() + "," + LB[i].getScore());
   }
}

Adding the true flag at the end of the StreamWriter should set the stream writer to work in append mode, which should add new lines rather than overwrite them on the file.

Upvotes: 1

Related Questions