2012-10-23 80 views
2

我正在嘗試將數組的內容寫入文本文件。我已經創建了文件,將文本框分配給數組(不確定是否正確)。現在我想將數組的內容寫入文本文件。 Streamwriter部分是我被困在底部的地方。不確定的語法。如何將數組的內容寫入文本文件? C#

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

回答

7

你可能只是這樣做:

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

+1:很不錯的LINQ的解決方案! –

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! 
     } 
    } 
4
using (FileStream fs = File.Open("scores.txt")) 
{ 
    StreamWriter sw = new StreamWriter(fs); 
    scoreArray.ForEach(r=>sw.WriteLine(r)); 
}