Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write contents of an array to a text file? C#

Tags:

arrays

c#

file

text

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);
like image 262
Boneyards Avatar asked Nov 29 '22 02:11

Boneyards


2 Answers

You could just do this:

System.IO.File.WriteAllLines("scores.txt",
    textBoxes.Select(tb => (double.Parse(tb.Text)).ToString()));
like image 84
Enigmativity Avatar answered Dec 05 '22 15:12

Enigmativity


using (FileStream fs = File.Open("scores.txt"))
{
    StreamWriter sw = new StreamWriter(fs);
    scoreArray.ForEach(r=>sw.WriteLine(r));
}
like image 36
opewix Avatar answered Dec 05 '22 15:12

opewix