C#读取txt文本内容行数
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ReadTxtLines
{
class Program
{
static void Main(string[] args)
{
int lines =readFileLines(" L:\\Code\\1.txt");
Console.WriteLine("该文件一共有" + lines + "行");
Console.ReadKey();
}
public static int readFileLines(string path) //这里的参数是txt所在路径
{
int lines = 0; //用来统计txt行数
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamReader sr = new StreamReader(fs);
while (sr.ReadLine() != null)
{
lines++;
}
fs.Close();
sr.Close();
return lines;
}
}
}