CSV To Datatable C#

Developed a class for reading CSV to Datatable in C#. Posting it on memorypointer.com so someone could find it useful

This class reads a CSV file to Datatable mapping field names in CSV to Data Columns and data to Data Rows

For exporting datatable to CSV i ll post another snippet, will post a link here when its done

Usage

var processor = new CSVProcessor(PathtoCSVFile, CSVFileName);

var datatable = processor.GetDatatable();

The Class CSVProcessor

public class CSVProcessor
{
OdbcConnection Conn;
private string m_FileName;

public CSVProcessor(string file,string filename)
{
// Connection to CSV file
string connStr = "Driver={Microsoft Text Driver (*.txt; *.csv)}; Dbq=" + file + "; Extensions=csv,txt ";
this.m_FileName = filename;

Conn = new OdbcConnection(connStr);
}

public DataTable GetDatatable()
{
var ds = new DataSet();
var DataAdapter = new OdbcDataAdapter("SELECT * FROM " + m_FileName, Conn);
try
{
// Fills data set with CSV
DataAdapter.Fill(ds);
return ds.Tables[0];

//' Catch errors
}
catch (OdbcException ex)
{
throw ex;
}
finally
{
DataAdapter.Dispose();
ds.Dispose();
}
}

~CSVProcessor()
{
//Cleanup
Conn.Dispose();

}

}


Get Free Email Updates!

Signup now and receive free offers, discounts & coupon codes

I will never give away, trade or sell your email address. You can unsubscribe at any time.

Leave a Reply

Your email address will not be published. Required fields are marked *

CommentLuv badge