首先,使用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