是否有一种简单的方法来编程确定文本文件中的行数?
当前回答
严重迟到的编辑:如果您使用的是。net 4.0或更高版本
File类有一个新的ReadLines方法,它懒惰地枚举行,而不是贪婪地将它们全部读入ReadAllLines这样的数组。所以现在你可以用下面的方法既高效又简洁:
var lineCount = File.ReadLines(@"C:\file.txt").Count();
原来的答案
如果你不太在意效率,你可以这样写:
var lineCount = File.ReadAllLines(@"C:\file.txt").Length;
对于一个更有效的方法,你可以这样做:
var lineCount = 0;
using (var reader = File.OpenText(@"C:\file.txt"))
{
while (reader.ReadLine() != null)
{
lineCount++;
}
}
编辑:在回答有关效率的问题时
The reason I said the second was more efficient was regarding memory usage, not necessarily speed. The first one loads the entire contents of the file into an array which means it must allocate at least as much memory as the size of the file. The second merely loops one line at a time so it never has to allocate more than one line's worth of memory at a time. This isn't that important for small files, but for larger files it could be an issue (if you try and find the number of lines in a 4GB file on a 32-bit system, for example, where there simply isn't enough user-mode address space to allocate an array this large).
在速度方面,我不期望它有很多。ReadAllLines可能有一些内部优化,但另一方面,它可能必须分配大量内存。我猜ReadAllLines可能对小文件更快,但对大文件明显更慢;尽管唯一的方法是用秒表或代码分析器来测量。
其他回答
计算回车/换行次数。我相信在unicode中它们仍然分别是0x000D和0x000A。这样你就可以根据自己的意愿来决定是否要同时处理两个角色
最简单的:
int lines = File.ReadAllLines("myfile").Length;
您可以快速地读入它,并增加一个计数器,只需使用一个循环来增加,对文本不做任何操作。
try {
string path = args[0];
FileStream fh = new FileStream(path, FileMode.Open, FileAccess.Read);
int i;
string s = "";
while ((i = fh.ReadByte()) != -1)
s = s + (char)i;
//its for reading number of paragraphs
int count = 0;
for (int j = 0; j < s.Length - 1; j++) {
if (s.Substring(j, 1) == "\n")
count++;
}
Console.WriteLine("The total searches were :" + count);
fh.Close();
} catch(Exception ex) {
Console.WriteLine(ex.Message);
}
如果你说的简单是指易于破译但效率很低的代码行?
string[] lines = System.IO.File.RealAllLines($filename);
int cnt = lines.Count();
这可能是知道行数的最快方法。
你还可以这样做(取决于你是否在缓冲它)
#for large files
while (...reads into buffer){
string[] lines = Regex.Split(buffer,System.Enviorment.NewLine);
}
还有许多其他的方法,但上面的一种可能是你会选择的。
推荐文章
- 何时使用IList,何时使用List
- ConfigurationManager。AppSettings在.NET Core 2.0中可用?
- 在c#的控制台应用程序中使用'async
- 在单元测试中设置HttpContext.Current.Session
- 如何开始开发Internet Explorer扩展?
- 更新行,如果它存在,否则插入逻辑实体框架
- 在什么情况下SqlConnection会自动被征召到环境事务范围事务中?
- 用c#解析JSON
- Windows窗体中的标签的换行
- 为什么在c#中使用finally ?
- 为什么我不能在c#中有抽象静态方法?
- net HttpClient。如何POST字符串值?
- 我如何使一个方法的返回类型泛型?
- 何时处理CancellationTokenSource?
- 如何获取正在执行的程序集版本?