简体   繁体   English

如何使用 Streamwriter 在新行上编写代码

[英]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嗨,我需要在.txt 中创建一个列表,但是使用这些代码我只能写入数据,并且键入只会覆盖第一个

        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

    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;
    }
}

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.在 StreamWriter 末尾添加 true 标志应该将 stream 写入器设置为在 append 模式下工作,这应该在文件上添加新行而不是覆盖它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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