只读一次文件的下一行

我有一个应用程序从文本文件中读取信息,然后对它们进行分类并将它们放到数据库中。 对于一个类别,我需要检查当前行之后的行并查找某个关键字?

我如何阅读这一行? 这个应该在streamreader已经打开当前行时发生….

我在VS2010上使用c#。

编辑

下面的所有代码都是一段时间(!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类型……! 这就是为什么我真的不喜欢阅读所有线路并保持跟踪!

简单地使用

  string[] lines = File.ReadAllLines(filename); 

并使用for (int i = 0; i < lines.Length; i ++)循环处理该文件。

对于大文件,只需缓存“上一行”或执行带外ReadLine()。

这是一个成功处理当前行的习惯用法,同时下一行已经可用:

 public void ProcessFile(string filename) { string line = null; string nextLine = null; using (StreamReader reader = new StreamReader(filename)) { line = reader.ReadLine(); nextLine = reader.ReadLine(); while (line != null) { // Process line (possibly using nextLine). line = nextLine; nextLine = reader.ReadLine(); } } } 

这基本上是一个队列 ,其中最多有两个项目,或“一行预读”。

编辑:简化。

你能再次调用reader.ReadLine()吗? 或者您是否需要在循环的下一次迭代中使用该行?

如果它是一个相当小的文件,您是否考虑过使用File.ReadAllLines()读取整个文件? 这可能会使它更简单,虽然在其他方面显然不那么干净,而且对于大文件来说更需要内存。

编辑:这里有一些代码作为替代:

 using (TextReader reader = File.OpenText(filename)) { string line = null; // Need to read to start with while (true) { if (line == null) { line = reader.ReadLine(); // Check for end of file... if (line == null) { break; } } if (line.Contains("Magic category")) { string lastLine = line; line = reader.ReadLine(); // Won't read again next iteration } else { // Process line as normal... line = null; // Need to read again next time } } } 

您可以在调用ReadLine之后保存流的位置,然后回到该位置。 然而,这是非常低效的。

我将ReadLine的结果存储到“缓冲区”中,并在可能时使用该缓冲区作为源。 如果为空,请使用ReadLine。

我不是一个文件IO专家……但为什么不这样做:

在开始阅读行之前,声明两个变量。

 string currentLine = string.Empty string previousLine = string.Empty 

然后在你读书的时候……

 previousLine = currentLine; currentLine = reader.ReadLine();