C# 如何一次一行读取CSV文件并解析出关键字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15560011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read a CSV file one line at a time and parse out keywords
提问by Steve
I am new to C# and I have started using StreamReader
. I am trying to read a file one line at a time and output the line when it matches a specific keyword like "I/RPTGEN".
我是 C# 新手,我已经开始使用StreamReader
. 我试图一次读取一个文件,并在它匹配特定关键字(如“I/RPTGEN”)时输出该行。
So far I figured out how to read the entire file into a string, but I'm having trouble figuring out how to just read it one line at a time.
到目前为止,我想出了如何将整个文件读入一个字符串,但我无法弄清楚如何一次只读取一行。
My code so far is this.
到目前为止,我的代码是这样的。
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();
}
}
}
}
Plus here is a sample of one line in the file.
另外这里是文件中一行的示例。
Advisory,2/27/2013 12:00:44 AM,I/RPTGEN (cadinterface),I/RPTGEN Failed - Error 500 - Internal Server Error - returned for a report request (check log for URL).
咨询,2/27/2013 12:00:44 AM,I/RPTGEN(cadinterface),I/RPTGEN 失败 - 错误 500 - 内部服务器错误 - 为报告请求返回(检查 URL 的日志)。
采纳答案by Steve
If your CSV file contains just one line the ReadToEnd
could be acceptable, but if you have a log file composed of more than one line then it is better to read line by line using ReadLine
of the StreamReader
object
如果您的CSV文件只包含一条线ReadToEnd
是可以接受的,但如果你有一个以上的线组成的,然后日志文件最好是使用以逐行读取ReadLine
的的StreamReader
对象
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);
}
}
}
回答by ClearLogic
Another way to read one line at a time is:
一次读取一行的另一种方法是:
var searchItem = "Error 500";
var lines = File.ReadLines("c:/temp/ESMDLOG.csv");
foreach (string line in lines)
{
if (line.Contains(searchItem))
{
Console.WriteLine(line);
}
}