2013-03-21 32 views
10

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

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

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

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 /2013分之27上午12时00分44秒,I/RPTGEN(cadinterface),I/RPTGEN失败 - 错误500 - 内部服务器错误 - 返回报告请求(查看日志的URL) 。

+5

@Tosi他的问题是在标题为“如何读取CSV文件一行的时间和解析出关键字”。不要这么苛刻。 – 2013-03-21 23:40:04

回答

18

如果您的CSV文件只包含一个行ReadToEnd是可以接受的,但如果你有一个以上的线组成的,然后日志文件最好是使用ReadLineStreamReader对象的行改为线

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); 
     } 
    } 
} 
+0

谢谢大家的答案。它让我更接近完成我的项目。 – Steve 2013-03-26 19:02:14

+0

如果我正在查找多个关键字(如日期和序列号)以及如果在我的CSV中有多个包含Date的关键字(例如, ExpirationDate与Just Date,我如何控制要查找哪些关键字?非常感谢! – 2014-05-16 16:40:26

+0

对不起,但目前的信息我无法回答。如何在指定所有要求的情况下提出新的问题?更多的人比我只会看你的问题。当然,你可以添加一个链接回到这个问题,并通过另一个链接通知我这里的新问题。 – Steve 2014-05-16 16:57:04

6

另一种方式为一次读取一行是:

var searchItem = "Error 500"; 

var lines = File.ReadLines("c:/temp/ESMDLOG.csv"); 

foreach (string line in lines) 
{ 
    if (line.Contains(searchItem)) 
    { 
     Console.WriteLine(line); 
    } 
}