清点文件中行数的 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
广告