清點檔案中行數的 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

更新於: 22-6 月-2020

2K+ 瀏覽

開創你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.