如何一次读取一行CSV文件并解析出关键字

我是C#的新手,我已经开始使用StreamReader 。 我试图一次读取一行文件,并在匹配特定关键字“I / RPTGEN”时输出该行。

到目前为止,我想出了如何将整个文件读入一个字符串,但我无法弄清楚如何一次只读一行。

到目前为止我的代码是这样的。

 using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication5 { class Test { public static void Main() { try { using (StreamReader sr = new StreamReader("c:/temp/ESMDLOG.csv")) { String line = sr.ReadToEnd(); Console.WriteLine(line); Console.ReadLine(); } } catch (Exception e) { Console.WriteLine("The File could not be read:"); Console.WriteLine(e.Message); Console.ReadLine(); } } } } 

另外,这里是文件中一行的示例。

咨询,2/27/2013 12:00:44 AM,I / RPTGEN(cadinterface),I / RPTGEN失败 – 错误500 – 内部服务器错误 – 为报告请求返回(检查URL的日志)。

如果您的CSV文件只包含一行,则ReadToEnd可以接受,但如果您有一个由多行组成的日志文件,那么最好使用StreamReader对象的ReadLine逐行读取

 using (StreamReader sr = new StreamReader("c:/temp/ESMDLOG.csv")) { string currentLine; // currentLine will be null when the StreamReader reaches the end of file while((currentLine = sr.ReadLine()) != null) { // Search, case insensitive, if the currentLine contains the searched keyword if(currentLine.IndexOf("I/RPTGEN", StringComparison.CurrentCultureIgnoreCase) >= 0) { Console.WriteLine(currentLine); } } } 

另一种一次读取一行的方法是:

 var searchItem = "Error 500"; var lines = File.ReadLines("c:/temp/ESMDLOG.csv"); foreach (string line in lines) { if (line.Contains(searchItem)) { Console.WriteLine(line); } }