是否有一种简单的方法来编程确定文本文件中的行数?
当前回答
您可以快速地读入它,并增加一个计数器,只需使用一个循环来增加,对文本不做任何操作。
其他回答
您可以快速地读入它,并增加一个计数器,只需使用一个循环来增加,对文本不做任何操作。
计算回车/换行次数。我相信在unicode中它们仍然分别是0x000D和0x000A。这样你就可以根据自己的意愿来决定是否要同时处理两个角色
您可以启动“wc.exe”可执行文件(UnixUtils附带,不需要安装)作为外部进程运行。它支持不同的行数方法(如unix vs mac vs windows)。
严重迟到的编辑:如果您使用的是。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可能对小文件更快,但对大文件明显更慢;尽管唯一的方法是用秒表或代码分析器来测量。
如果你说的简单是指易于破译但效率很低的代码行?
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);
}
还有许多其他的方法,但上面的一种可能是你会选择的。
推荐文章
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- 在ASP中选择Tag Helper。NET Core MVC
- 如何在没有任何错误或警告的情况下找到构建失败的原因
- 跨线程操作无效:控件“textBox1”从创建它的线程以外的线程访问
- 否ConcurrentList<T>在。net 4.0?
- 在c#中解析字符串为日期时间