Đầu tiên, tạo tệp bằng lớp StreamWriter và thêm nội dung vào đó -
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");
} Bây giờ sử dụng phương thức ReadAllLines () để đọc tất cả các dòng. Cùng với đó, thuộc tính Độ dài sẽ được sử dụng để tính số dòng -
int count = File.ReadAllLines("hello.txt").Length; Đây là mã hoàn chỉnh -
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("Number of lines: "+count);
}
} Đầu ra
Number of lines: 3