Thursday, September 21, 2017

How to quickly parse the CSV file into an array or Table in C#?

I just receive an csv file that i need to process it and grab email from email column and add the cotent to email message body from the content column.


actually we can handle it in two way, the first one, we can use the TextFieldParser from VisualBasic.FileIO to read the data into the parser then process them.



        List<string[]> parsedData = new List<string[]>();
            string[] fields;

            //string line = parser.ReadLine();

            try
            {
                TextFieldParser parser = new TextFieldParser(@"c:\temp\sample.csv");
                parser.TextFieldType =Microsoft.VisualBasic.FileIO.FieldType.Delimited;
                parser.SetDelimiters(",");

                while (!parser.EndOfData)
                {
                    fields = parser.ReadFields();
                    parsedData.Add(fields);
                }

                parser.Close();

            }
            catch (Exception e)
            {
                //MessageBox.Show(e.Message);
            }



the second one, you can download the CSVHelper from Nuget Package Management Windows




             List<string[]> parsedData = new List<string[]>();
            using (StreamReader reader = File.OpenText(@"c:\temp\sample.csv"))
            {
                var parser = new CsvParser(reader);

                while (true)
                {
                    var row = parser.Read();

                    if (row == null)
                    {
                        break;
                    }
                    else
                    {
                        parsedData.Add(row);
                    }
                }
            }


No comments:

Post a Comment