仅读取文件的下一行一次
我有一个应用程序,它从文本文件中读取信息,然后对它们进行分类并将它们放入数据库中。对于一个类别,我需要检查当前行之后的行并查找某个关键字?
我如何阅读这一行?当流读取器当前行已打开时,应该会发生这种情况...
我在 VS2010 上使用 c#。
编辑:
下面的所有代码都在 while (!sReader.EndOfStream) 循环中
string line = sReader.ReadLine(); //Note: this is used way above and lots of things are done before we come to this loop
for (int i = 0; i < filter_length; i++)
{
if (searchpattern_queries[i].IsMatch(line) == true)
{
logmessagtype = selected_queries[i];
//*Here i need to add a if condition to check if the type is "RESTARTS" and i need to get the next line to do more classification. I need to get that line only to classify the current one. So, I'd want it to be open independently *
hit = 1;
if (logmessagtype == "AL-UNDEF")
{
string alid = AlarmID_Search(line);
string query = "SELECT Severity from Alarms WHERE ALID like '" +alid +"'";
OleDbCommand cmdo = new OleDbCommand(query, conn);
OleDbDataReader reader;
reader = cmdo.ExecuteReader();
while (reader.Read())
{
if (reader.GetString(0).ToString() == null)
{ }
else
{
string severity = reader.GetString(0).ToString();
if (severity == "1")
//Keeps going on.....
此外,打开的 .log 文件可能会转到最多 50 Mb 类型...!这就是为什么我不太喜欢阅读所有行并跟踪!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一个在下一行已经可用的情况下处理当前行的习惯用法:
这基本上是一个队列,其中最多包含两个项目,或“一行预读”。
编辑:简化。
Here is an idiom to process the current line you while having the next line already available:
This is basically a queue with a maximum of two items in it, or "one line read-ahead".
Edit: Simplified.
只需使用
for (int i = 0; i 循环来使用和处理该文件。
对于大文件,只需缓存“前一行”或执行带外 ReadLine()。
Simply use
and process the file with a
for (int i = 0; i < lines.Length; i ++)
loop.For a big file, simply cache the 'previous line' or do an out-of-band ReadLine().
你能不能再次调用
reader.ReadLine()
?或者问题是您需要在循环的下一次迭代中使用该行?如果它是一个相当小的文件,您是否考虑过使用 File.ReadAllLines() 读取整个文件?这可能会让它变得更简单,尽管在其他方面显然不太干净,并且对于大文件来说更需要内存。
编辑:这里有一些代码作为替代:
Can you not just call
reader.ReadLine()
again? Or is the problem that you then need to use the line in the next iteration of the loop?If it's a reasonably small file, have you considered reading the whole file using
File.ReadAllLines()
? That would probably make it simpler, although obviously a little less clean in other ways, and more memory-hungry for large files.EDIT: Here's some code as an alternative:
您可以保存流的位置,然后在调用 ReadLine 后,返回到该位置。然而,这是相当低效的。
我会将 ReadLine 的结果存储到“缓冲区”中,并在可能的情况下使用该缓冲区作为源。当它为空时,使用ReadLine。
You could save the position of the stream then after calling ReadLine, seek back to that position. However this is pretty inefficient.
I would store the result of ReadLine into a "buffer", and when possible use that buffer as a source. When it is empty, use ReadLine.
我并不是真正的文件 IO 专家...但为什么不做这样的事情:
在开始阅读行之前声明两个变量。
那么当你在阅读的时候...
I am not really a file IO expert... but why not do something like this:
Before you start reading lines declare two variables.
Then while you are reading...