清點檔案中行數的 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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式語言
C++
C#
MongoDB
MySQL
Javascript
PHP