2012-10-23 3 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)); 
} 
관련 문제