4

I'm trying to write the contents of an array to a text file. I've created the file, assigned text boxes to the array (not sure if correctly). Now I want to write the contents of the array to a text file. The streamwriter part is where I'm stuck at the bottom. Not sure of the syntax.

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);
Dave Zych
  • 21,581
  • 7
  • 51
  • 66
Boneyards
  • 83
  • 1
  • 2
  • 9

5 Answers5

15

You could just do this:

System.IO.File.WriteAllLines("scores.txt",
    textBoxes.Select(tb => (double.Parse(tb.Text)).ToString()));
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • Love this. No hassling with opening and closing files or creating stream writers, etc. Just a one-liner that works. – Mike K Mar 05 '19 at 18:16
6
using (FileStream fs = File.Open("scores.txt"))
{
    StreamWriter sw = new StreamWriter(fs);
    scoreArray.ForEach(r=>sw.WriteLine(r));
}
opewix
  • 4,993
  • 1
  • 20
  • 42
1

You may try to write to the file before you close it... after the FileStream fs = File.Create("scores.txt"); line of code.

You may also want to use a using for that. Like this:

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!
        }
    }
Miguel Angelo
  • 23,796
  • 16
  • 59
  • 82
0

You can convert your List to an array then write the array to a textfile

double[] myArray = scoreArray.ToArray();
File.WriteAllLines("scores.txt",
  Array.ConvertAll(myArray, x => x.ToString()));
lue
  • 449
  • 5
  • 16
Herbert
  • 75
  • 8
0

Just do this to resolve your issue

Form.Close();

asasas
  • 1
  • 1
    While this may answer the question, it would be best if you could provide a more in-depth explanation for why it does so. – nik7 Apr 21 '21 at 20:42