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(); } } }
loading...
About Hardono
Incoming Search
net read csv file
Excellent! Worked straight away. This is just what I needed. Top work!
Cheers mate 🙂
Did great job for me.
Good one…
But need to make some changes with escape characters.
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 🙁
Thanks Hardono !