2007
04.17

Reading CSV File with .NET

During the course of time, I often required to write solutions which involve reading CSV (Comma Separated Values) Files. After repeating the same thing for a few times, I decided to write a component that will parse the CSV file and return a DataTable.

To use the the component is really simple. First you need to declare the object,

    CsvDataSource.CsvDataSource src = new CsvDataSource.CsvDataSource();

and then read the CSV file. There are three possible way to read the CSV:

    //Using comma as character separator, first line is NOT treated as column names
    DataTable dt1 = src.ReadFile("input.csv"); 

    //Using comma as separator character, first line is treated as column names
    DataTable dt2 = src.ReadFile("input.csv", true); 

    //Using pipe (|) as separator character, first line is treated as column names
    DataTable dt3 = src.ReadFile("input.csv", true, '|'); 

The complete source code as follows: Download the class source code.

Simple demo using Command Line Application:

/* Demo of CsvDataSource using Command Line Application
 * (c) 2007 Hardono Arifanto
 * http://sodeve.net
 */
using System;
using System.Collections.Generic;
using System.Text;
using CsvDataSource;
using System.Data;

namespace CsvDataSourceDemo
{
    class Program
    {
        private static void printHelp()
        {
            Console.WriteLine(@"Demo for CsvDataSource.
    Usage: CsvDataSourceDemo [inputfile.csv]");
        }
        static void Main(string[] args)
        {
            DataTable dt;
            if (args.Length > 0)
            {
                CsvDataSource.CsvDataSource src = new CsvDataSource.CsvDataSource();
                dt = src.ReadFile(args[0],true,',');
                //Display the DataTable content
                foreach (DataColumn dc in dt.Columns)
                {
                    Console.Write(dc.ColumnName + "t");
                }
                Console.WriteLine();
                foreach (DataRow dr in dt.Rows)
                {
                    for(int i=0; i < dt.Columns.Count; i++)
                    {
                        Console.Write(dr[i] + "t");
                    }
                    Console.WriteLine();
                }
            }
            else
                printHelp();
        }
    }
}
GD Star Rating
loading...
Reading CSV File with .NET, 5.0 out of 5 based on 1 rating

Incoming Search Term

net read csv file

Advertise Here

5 comments so far

Add Your Comment
  1. Excellent! Worked straight away. This is just what I needed. Top work!

  2. Cheers mate 🙂

  3. Did great job for me.
    Good one…

    But need to make some changes with escape characters.

  4. Hi Sini,

    Could you describe more ? 🙂

    Anyway, I have removed the complete source code and replace it with a download-able file.

    Apparently the syntax highlighter messed up the original source code 🙁

  5. Thanks Hardono !