使用C#从大文本文件中读取最后150行 [英] Read Last 150 lines from the large text file using C#

查看:107
本文介绍了使用C#从大文本文件中读取最后150行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好b $ b



我有一个包含大量数据的文本文件。我想阅读最后150行数据,在150行数据中我想根据某些部分搜索标准过滤数据。



任何帮助.. 。

Hi

I Have a text file with huge data. I want to read the last 150 lines of data and within the 150 lines of data i want to filter the data based on some partiucular search criteria.

Any Help...

推荐答案

很容易看出,如果不读取所有之前的行,就无法读取最后N行。这是因为线条的长度不同,您事先并不知道。在您全部阅读之前,您不知道文件中下一行的位置。此外,您需要在内存中保留至少150行,因为您不知道有多少行。最简单的方法是:

http://msdn.microsoft.com/ en-us / library / s2tte0y1.aspx [ ^ ]。



当所有行都进入数组时,如果数组元素的数量大于或等于,则使用最后150行150,或者其他所有行。



巨大的数据?我希望由于线路很多,不是因为线路太长,否则10线路可能太多。然后,想法是:制作一个150 + 150行的窗口,将行读入150行的窗口,您可能使用也可能不使用。以150块为单位读取文件。如果您的上一个块少于150(非常可能,对吧?),则需要第二个数组。然后你将需要上一个窗口的数据。



替代解决方案:读取所有行但不记得它们,只记住文件中每行的位置。在此循环之后,您将知道它们在文件中的行数和位置。然后你需要第二个循环:只读你需要的行。



-SA
It is easy to see that is is impossible to read last N lines without reading all previous lines. This is because the lines have different lengths which you don't know in advance. Before you read them all, you don't know the location of the next line in the file. Moreover, you need to keep at least 150 lines in memory, because you don't know how many lines are there. The simplest method is this:
http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx[^].

When you have all lines into the array, you use the last 150 lines if the number of array elements is greater or equal to 150, or all lines otherwise.

Huge data? I hope due to many lines, not because the lines are too long, otherwise 10 lines could be too much. Then, the idea is: make a window of 150+150 lines, read lines into a window of 150 lines, which you may or may not use. Read the file in chunks of 150. The second array is needed in case your last chunk is less then 150 (very likely, right?). Then you will need data from the previous window.

Alternative solution: read all lines but don't remember them, only remember positions of each line in file. After this loop, you will know the number of lines and positions of them in file. Then you will need a second loop: read only the lines you need.

—SA


正如我所见,你想要一些类似于linux tail 实用程序的东西。检查一下:在C#.NET中 linuxtail -f命令 [ ^ ]
As I see, you want something similar to linux tail utility. Check this: linux "tail -f" Command in C#.NET[^]


您可以尝试以下代码语法。



List< string> text = File.ReadLines(file.txt)。Reverse()。Take(2)。ToList();



更多信息请访问此网址
You can try bellow code syntax.

List<string> text = File.ReadLines("file.txt").Reverse().Take(2).ToList();

for more information visit this URL.


这篇关于使用C#从大文本文件中读取最后150行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆