C# 程序计算文件中的行数
csharpprogrammingserver side programming更新于 2025/9/16 18:52:00
首先,使用 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

