C#을 사용하여 txt 파일에서 읽고 쓰려고합니다. 현재 목록에있는 이름을 읽고이를 사용자에게 보여주고 다른 이름을 묻고 목록에 추가하는 프로그램을 작성하고 있습니다. 독서는 훌륭하지만 글쓰기에 문제가 있습니다.txt 파일에서 읽기 및 쓰기
코드는 CSC를 사용하여 고급 컴파일하고 그것을 잘 실행하지만 내가 추가하고 Enter 키를 눌러 이름을 입력 한 후, 나는 FileIO.exe 문제와 요구가 발생했습니다
말 팝업 창을 얻을 닫으십시오.
어떤 문제인지 알고 싶습니다.
using System;
using System.IO;
public class Hello1
{
public static void Main()
{
int lines = File.ReadAllLines("Name.txt").Length;
string[] stringArray = new string[lines + 1];
StreamReader reader = new StreamReader("Name.txt");
for(int i = 1;i <=lines;i++){
stringArray[i-1] = reader.ReadLine();
}
for (int i = 1;i <=stringArray.Length;i++){
Console.WriteLine(stringArray[i-1]);
}
Console.WriteLine("Please enter a name to add to the list.");
stringArray[lines] = Console.ReadLine();
using (System.IO.StreamWriter writer = new System.IO.StreamWriter("Name.txt", true)){
writer.WriteLine(stringArray[lines]);
}
}
}
독자에게도 'using'문을 사용하십시오. '(var reader = new StreamReader ("Name.txt")) {...}' –
스트림을 다시 열기 전에 닫아서 작성하십시오. 더 나은 'using'문 사용하기 –
왜'File.ReadAllLines'을 사용하고, 길이를 가지고 다시 읽는가? 이것을 달성하기위한 * 더 간단한 방법이 있습니다. –