C#
(C#) 텍스트 파일 읽기 ReadLine ReadToEnd
코딩ABC
2023. 6. 2. 21:37
반응형
C#에서 텍스트 파일을 읽어 들이는 방법입니다.
1. 한 줄씩 읽기
다음 코드는 ReadLine 메서드를 이용해서 텍스트 파일에서 한 줄씩 읽는 코드입니다.
using System;
using System.IO;
public class Program
{
public static void Main()
{
string path = @"c:\temp\text.txt";
string line;
using (StreamReader sr = new StreamReader(path))
{
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
2. 한번에 끝까지 읽기
다음 코드는 텍스트 파일은 한꺼번에 읽는 코드입니다.
using System;
using System.IO;
public class Program
{
public static void Main()
{
string path = @"c:\temp\text.txt";
using (StreamReader sr = new StreamReader(path))
{
Console.WriteLine(sr.ReadToEnd());
}
}
}
반응형