먼저 StreamWriter 클래스를 사용하여 파일을 만들고 여기에 내용을 추가합니다. -
using (StreamWriter sw = new StreamWriter("hello.txt")) {
sw.WriteLine("This is demo line 1");
sw.WriteLine("This is demo line 2");
sw.WriteLine("This is demo line 3");
} 이제 ReadAllLines() 메서드를 사용하여 모든 줄을 읽습니다. 이를 통해 Length 속성을 사용하여 줄 수 -
를 얻을 수 있습니다.int count = File.ReadAllLines("hello.txt").Length; 다음은 전체 코드입니다 -
예
using System;
using System.Collections.Generic;
using System.IO;
public class Program {
public static void Main() {
using (StreamWriter sw = new StreamWriter("hello.txt")) {
sw.WriteLine("This is demo line 1");
sw.WriteLine("This is demo line 2");
sw.WriteLine("This is demo line 3");
}
int count = File.ReadAllLines("hello.txt").Length;
Console.WriteLine("Number of lines: "+count);
}
} 출력
Number of lines: 3