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

后端 未结 4 888
深忆病人
深忆病人 2021-01-01 04:57

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 con

相关标签:
4条回答
  • 2021-01-01 05:34

    You could just do this:

    System.IO.File.WriteAllLines("scores.txt",
        textBoxes.Select(tb => (double.Parse(tb.Text)).ToString()));
    
    0 讨论(0)
  • 2021-01-01 05:36

    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!
            }
        }
    
    0 讨论(0)
  • 2021-01-01 05:39
    using (FileStream fs = File.Open("scores.txt"))
    {
        StreamWriter sw = new StreamWriter(fs);
        scoreArray.ForEach(r=>sw.WriteLine(r));
    }
    
    0 讨论(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()));
    
    0 讨论(0)
提交回复
热议问题