Thursday, 28 March 2013

Search string in CSV

Question is:

I have a string called inputstring. I'd like to search a CSV file to find all instances of the inputstring? How is this done in c#?

Ans:

namespace CSV_search_string

{

    class Program

    {

        static void Main(string[] args)

        {

            string csvFile = "SciFi Books.csv";

            string searchString = "Fred Hoyle";

            char csvSeparator = ',';

 

            foreach (string line in File.ReadLines(csvFile))

                foreach (string value in line.Replace("\"", "").Split('\r', '\n', csvSeparator))

                    if (value.Trim() == searchString.Trim()) // case sensitive

                        Console.WriteLine("[ {0} ] found in: {1}", value, line);

 

            Console.ReadKey();

        }

    }

}

No comments:

Post a Comment