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);
4

5 回答 5

15

你可以这样做:

System.IO.File.WriteAllLines("scores.txt",
    textBoxes.Select(tb => (double.Parse(tb.Text)).ToString()));
于 2012-10-23T03:33:35.553 回答
6
using (FileStream fs = File.Open("scores.txt"))
{
    StreamWriter sw = new StreamWriter(fs);
    scoreArray.ForEach(r=>sw.WriteLine(r));
}
于 2012-10-23T03:31:43.303 回答
1

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

您可能还想使用 a 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!
        }
    }
于 2012-10-23T03:31:39.780 回答
0

您可以将您转换List为数组,然后将数组写入文本文件

double[] myArray = scoreArray.ToArray();
File.WriteAllLines("scores.txt",
  Array.ConvertAll(myArray, x => x.ToString()));
于 2020-03-13T17:56:54.100 回答
0

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

Form.Close();

于 2021-04-21T19:36:23.493 回答