Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C#으로 텍스트 파일의 줄 수 계산하기 – StreamWriter와 ReadAllLines 활용법

C#에서 텍스트 파일의 줄 수를 계산하려면 StreamWriter 클래스로 파일을 생성한 뒤, File.ReadAllLines() 메서드와 Length 속성을 조합하면 아주 간단하게 구현할 수 있습니다.

1. StreamWriter로 파일 생성 및 내용 작성

먼저 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");
}

2. ReadAllLines()로 줄 수 계산하기

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

참고 사항

ReadAllLines()는 파일 전체를 한꺼번에 메모리에 불러오기 때문에 용량이 큰 파일에는 적합하지 않습니다. 대용량 파일을 처리할 때는 StreamReader를 사용해 한 줄씩 읽으면서 카운트하는 방식이 더 효율적입니다. 또한 StreamWriter는 기본적으로 기존 파일을 덮어쓰므로, 내용을 이어서 추가하고 싶다면 생성자에 true 값을 전달하면 됩니다.