Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

c# - How to read a CSV file one line at a time and parse out keywords

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".

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...