【问题标题】:Add a label in to a list that reads a file in C#将标签添加到在 C# 中读取文件的列表中
【发布时间】:2020-11-25 15:16:10
【问题描述】:

您好,我是一名新程序员,我有一个项目,我希望将分数保存在列表或数组中(这两个用玩家的用户名读取我的文件)我已经写过了,但我没有知道为什么不写了

这是我的文本文件“name.txt”:

Timmy1
Nick12
Mary3

这是我的代码(label6 是分数):

List<string> lines = File.ReadAllLines("name.txt").ToList();

 void game(int x,string label)
        {
            label8.Text = label;
            randomImage = random.Next(1, x);
            pictureBox2.ImageLocation = "dice/" + randomImage.ToString() + ".png";
            int x1, y1;
            x1 = random.Next(panel1.Width - pictureBox2.Width);
            y1 = random.Next(panel1.Height - pictureBox2.Height);
            pictureBox2.Location = new Point(x1, y1);
            countDown--;

            label3.Text = countDown.ToString();
          
            for (int i = 0; i < lines.Count; i++ ) {
                
                if (countDown == 0)
                {
                    timer1.Enabled = false;
                    pictureBox1.Enabled = false;
                    DialogResult dialogResult = MessageBox.Show("Play Again?", "Game Over!", MessageBoxButtons.YesNo);
                    if (dialogResult == DialogResult.Yes)
                    { 
                        lines.Append(label6.Text);
                        Form4 f4 = new Form4(label2.Text, level);
                        this.Close();
                        f4.Show();
                        break;
                    }
                    else
                    {
                        Form3 f3 = new Form3(label2.Text);
                        this.Hide();
                        f3.Show();
                        break;
                    }
                }
            }

我希望文本文件 name.txt 的结果是这样的:

Timmy1
*Score of the player Timmy1*
Nick12
*Score of the player Nick12*
Mary3
*Score of the player Mary3*

【问题讨论】:

  • 您没有将这些行写回文件(假设您正在尝试这样做)。提示:要将所有行写入文件,有一个与File.ReadAllLines()非常相似的调用

标签: c# arrays list file add


【解决方案1】:

它没有写它,因为你从来没有告诉你的程序这样做。 您正在读取一个文件并将其行存储在List&lt;string&gt; 中。稍后您将一些值添加到此列表中,但您从未将修改后的列表写入文件。

您必须在代码中的某处调用如下代码:

File.WriteAllLines("name.txt", lines);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-10
    • 2017-05-25
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 2021-09-13
    相关资源
    最近更新 更多