텍스트 파일을 한 줄씩 읽는 방법에는 여러 가지가 있습니다. 여기에는 StreamReader.ReadLine, File.ReadLines 등이 포함됩니다. 로컬 시스템에 아래와 같은 줄이 있는 텍스트 파일이 있다고 가정해 보겠습니다.

StreamReader.ReadLine 사용 -
C# StreamReader는 지정된 인코딩의 스트림으로 문자를 읽는 데 사용됩니다. StreamReader.Read 메서드는 입력 스트림에서 다음 문자 또는 다음 문자 집합을 읽습니다. StreamReader는 문자, 블록, 줄 또는 모든 콘텐츠를 읽는 메서드를 제공하는 TextReader에서 상속됩니다.
예시
using System;
using System.IO;
using System.Text;
namespace DemoApplication{
public class Program{
static void Main(string[] args){
using (var fileStream = File.OpenRead(@"D:\Demo\Demo.txt"))
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8)){
String line;
while ((line = streamReader.ReadLine()) != null){
Console.WriteLine(line);
}
}
Console.ReadLine();
}
}
} 출력
Hi All!! Hello Everyone!! How are you?
File.ReadLines 사용
File.ReadAllLines() 메서드는 텍스트 파일을 열고 파일의 모든 줄을 aIEnumerable
예시
using System;
using System.IO;
namespace DemoApplication{
public class Program{
static void Main(string[] args){
var lines = File.ReadLines(@"D:\Demo\Demo.txt");
foreach (var line in lines){
Console.WriteLine(line);
}
Console.ReadLine();
}
}
} 출력
Hi All!! Hello Everyone!! How are you?
File.ReadAllLines 사용
이것은 ReadLines와 매우 유사합니다. 그러나 IEnumerable
예시
using System;
using System.IO;
namespace DemoApplication{
public class Program{
static void Main(string[] args){
var lines = File.ReadAllLines(@"D:\Demo\Demo.txt");
for (var i = 0; i < lines.Length; i += 1){
var line = lines[i];
Console.WriteLine(line);
}
Console.ReadLine();
}
}
} 출력
Hi All!! Hello Everyone!! How are you?