Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

โปรแกรม C# นับจำนวนบรรทัดในไฟล์

ใช้ File.ReadAllLines(path).Length อ่านทุกบรรทัดเป็น Array แล้วดู Length (เหมาะไฟล์เล็ก-ปานกลาง)

ตัวอย่างโค้ด

using System;
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

สำหรับไฟล์ใหญ่: ใช้ StreamReader อ่านทีละบรรทัดนับใน Loop เพื่อประหยัด Memory