C# 강좌 : 제 22강 - 텍스트파일 읽기 & 쓰기
텍스트 파일 읽기 쓰기(Text File Read & Write)
*.txt
파일이나 *.dat
파일의 텍스트(Text)
를 불러오거나 저장할할 수 있습니다.
경로 앞에 @
을 붙여야 하며, 한 줄 씩 읽을 경우 변수이름[index]
로 한 줄 씩 불러올 수 있습니다.
변수로 지정된 경로를 추가할 경우 @
앞에 추가해야합니다.
Namespace 선언
using System.IO;
파일을 읽거나 쓰기 위하여 namespace
에 System.IO
를 선언합니다.
텍스트 읽기(Read Text)
모든 줄 읽기(ReadAllText)
string 변수이름 = File.ReadAllText(@"경로");
//절대경로//
string text = File.ReadAllText(@"모든경로\TEXT_File.txt");
Console.WriteLine("{0}", text);
//상대경로//
string text = File.ReadAllText(@"..\..\TEXT_File.txt");
Console.WriteLine("{0}", text);
//상대경로-내문서//
string mydoc = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
string text = File.ReadAllText(mydoc + @"\TEXT_File.txt");
Console.WriteLine("{0}", text);
절대 경로
또는 상대 경로
를 이용하여 텍스트 파일의 모든 텍스트
를 한 번에
불러옵니다.
한 줄 씩 읽기(ReadAllLines)
string[] 변수이름 = File.ReadAllLines(@"경로");
//절대경로//
string[] lines = File.ReadAllLines(@"모든경로\TEXT_File.txt");
foreach (string show in lines)
{
Console.WriteLine("{0}", show);
}
//상대경로//
string[] lines = File.ReadAllLines(@"..\..\TEXT_File.txt");
foreach (string show in lines)
{
Console.WriteLine("{0}", show);
}
//상대경로-내문서//
string mydoc = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
string[] lines = File.ReadAllLines(mydoc + @"\TEXT_File.txt");
foreach (string show in lines)
{
Console.WriteLine("{0}", show);
}
절대 경로
또는 상대 경로
를 이용하여 텍스트 파일의 모든 텍스트
를 한 줄 씩
불러옵니다.
텍스트 쓰기(Write Text)
파일 쓰기(StreamWriter)
using (StreamWriter 변수이름 = new StreamWriter(@"경로", Boolean))
//상대경로//
string[] lines = { "First line", "Second line", "Third line" };
using (StreamWriter outputFile = new StreamWriter(@"..\..\New_TEXT_File.txt"))
{
foreach (string line in lines)
{
outputFile.WriteLine(line);
}
}
절대경로
또는 상대경로
를 이용하여 텍스트 파일의 텍스트
를 쓸 수 있습니다.
New_TEXT_File.txt에 First line
, Second line
, Third line
3줄의 구문을 만들어 생성합니다.
절대 경로
및 상대 경로
이용법은 위와 동일합니다.
덧붙여 쓰기(Added Write)
using (StreamWriter outputFile = new StreamWriter(@"..\..\New_TEXT_File.txt", true))
{
outputFile.WriteLine("Fourth Line");
}
파일의 마지막 줄
에 구문을 추가하여 작성합니다.
true
를 추가하여 파일을 새로 덧씌우지 않고 이어서 작성할 수 있게 합니다.
공유하기


댓글 남기기