Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing and polishing a CSV parser

Tags:

c#

parsing

As part of a recent project I had to read and write from a CSV file and put in a grid view in c#. In the end decided to use a ready built parser to do the work for me.

Because I like to do that kind of stuff, I wondered how to go about writing my own.

So far all I've managed to do is this:

//Read the header
            StreamReader reader = new StreamReader(dialog.FileName);
            string row = reader.ReadLine();
            string[] cells = row.Split(',');

            //Create the columns of the dataGridView
            for (int i = 0; i < cells.Count() - 1; i++)
            {
                DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
                column.Name = cells[i];
                column.HeaderText = cells[i];
                dataGridView1.Columns.Add(column);
            }

            //Display the contents of the file
            while (reader.Peek() != -1)
            {
                row = reader.ReadLine();
                cells = row.Split(',');
                dataGridView1.Rows.Add(cells);
            }

My question: is carrying on like this a wise idea, and if it is (or isn't) how would I test it properly?

like image 535
Tom Kealy Avatar asked Feb 13 '12 19:02

Tom Kealy


1 Answers

As a programming exercise (for learning and gaining experience) it is probably a very reasonable thing to do. For production code, it may be better to use an existing library mainly because the work is already done. There are quite a few things to address with a CSV parser. For example (randomly off the top of my head):

  • Quoted values (strings)
  • Embedded quotes in quoted strings
  • Empty values (NULL ... or maybe even NULL vs. empty).
  • Lines without the correct number of entries
  • Headers vs. no headers.
  • Recognizing different data types (e.g., different date formats).

If you have a very specific input format in a very controlled environment, though, you may not need to deal with all of those.

like image 160
Mark Wilkins Avatar answered Oct 13 '22 01:10

Mark Wilkins