File.ReadAllLines(path).Length đọc toàn bộ file vào mảng chuỗi và lấy độ dài mảng.
Ví dụ
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("Số dòng: " + count);
}
}
Kết quả
Số dòng: 3
Hiệu năng: Với file lớn, dùng StreamReader đọc từng dòng và đếm để tiết kiệm bộ nhớ.