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

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


ขั้นแรก สร้างไฟล์โดยใช้คลาส 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