c# 如何得到txt文件有多少行,代码如何实现

如题所述

第1个回答  2014-06-16
string path = "c:/abc.txt";
string[] strings = File.ReadAllLines(path);
strings.Length    // 行数

追问

追答

我这里 OK 啊,你的 VS 是什么版本

追问

我用的是2010版本,开发wp7程序,是不是和console不一样啊

追答

不是 console 的问题,你开发 wp7,.net framework被精简了,不知道被精简过后的 File 类还支持什么方法,任何一个 Read...()的方法都可以把

追问

我自己做了一个 不对呀
do//获得总行数
{
t = reader1.ReadLine();
lineno++;
} while (t == null);
line = --lineno;
line应该就是最后行数

追答string path = "c:/abc.txt";
IEnumerable<string> strings = File.ReadLines(path);
int line = 0;
foreach (string s in strings)
{
    line++;
}
line // 就是行数

 呃 只支持 File.ReadLine() 么 File.ReadLines()呢?

本回答被提问者采纳
第2个回答  2016-01-18
 try
{
int i=0;
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
this.ListBox1.Items.Add("line "); //增加读出的内容到listbox
i++;
}
this.TextBox1.Text=i.ToString(); 显示行数
}
}
catch
{
}
第3个回答  2014-06-16
用StreamReader打开文件,可以按行取得文件内容ReadLine,做个循环就知道有多少行了。
相似回答