如何将数组内容写入文本文件?C#

4

我想将一个数组的内容写入文本文件。我已经创建了文件,并将文本框分配给了数组(不确定是否正确)。现在我想将数组的内容写入文本文件。StreamWriter 的部分是我卡住的部分。不确定语法。

if ((!File.Exists("scores.txt"))) //Checking if scores.txt exists or not
{
    FileStream fs = File.Create("scores.txt"); //Creates Scores.txt
    fs.Close(); //Closes file stream
}
List<double> scoreArray = new List<double>();
TextBox[] textBoxes = { week1Box, week2Box, week3Box, week4Box, week5Box, week6Box, week7Box, week8Box, week9Box, week10Box, week11Box, week12Box, week13Box };

for (int i = 0; i < textBoxes.Length; i++)
{
    scoreArray.Add(Convert.ToDouble(textBoxes[i].Text));
}
StreamWriter sw = new StreamWriter("scores.txt", true);
5个回答

15

你可以这样做:

System.IO.File.WriteAllLines("scores.txt",
    textBoxes.Select(tb => (double.Parse(tb.Text)).ToString()));

太喜欢这个了。不需要烦恼打开和关闭文件或创建流编写器等等。只需要一个有效的一行命令即可。 - Mike K

6
using (FileStream fs = File.Open("scores.txt"))
{
    StreamWriter sw = new StreamWriter(fs);
    scoreArray.ForEach(r=>sw.WriteLine(r));
}

1

在关闭文件之前,您可以尝试向文件写入内容... 在 FileStream fs = File.Create("scores.txt"); 代码行之后。

您还可以使用 using 来实现这一点。 像这样:

if ((!File.Exists("scores.txt"))) //Checking if scores.txt exists or not
    {
        using (FileStream fs = File.Create("scores.txt")) //Creates Scores.txt
        {
            // Write to the file here!
        }
    }

0
你可以将你的 List 转换成数组,然后将数组写入文本文件。
double[] myArray = scoreArray.ToArray();
File.WriteAllLines("scores.txt",
  Array.ConvertAll(myArray, x => x.ToString()));

0

只需这样做即可解决您的问题

Form.Close();


1
虽然这可能回答了问题,但最好能够提供更深入的解释,说明为什么会这样。 - nik7

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接