How To Parse a CSV File Into a DataTable for Use In Your Code

The situation:

You have uploaded a CSV file, and you now need to do something with the data in your programming.

A Solution:

using System.Data;
using System.Data.OleDb;
using System.IO;

public static DataTable ParseCSV(string path, bool headerinfile)
{
	if ( !File.Exists(path) )
		return null;

	string headertext = "No";
	if ( headerinfile )
	{
		headertext = "Yes";
	}

	string full = Path.GetFullPath(path);
	string file = Path.GetFileName(full);
	string dir = Path.GetDirectoryName(full);

	//create the "database" connection string 
	string connString = "Provider=Microsoft.Jet.OLEDB.4.0;"
	  + "Data Source=\"" + dir + "\\\";"
	  + "Extended Properties=\"text;HDR=" + headertext + ";FMT=Delimited\"";

	//create the database query
	string query = "SELECT * FROM " + file;

	//create a DataTable to hold the query results
	DataTable dTable = new DataTable();

	//create an OleDbDataAdapter to execute the query
	OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);

	try
	{
		//fill the DataTable
		dAdapter.Fill(dTable);
	}
	catch ( InvalidOperationException /*e*/)
	{ throw; }

	dAdapter.Dispose();

	return dTable;
}

One thought on “How To Parse a CSV File Into a DataTable for Use In Your Code

  1. Pingback: How To Get Values from a DataTable without Crashing if a Column Doesn’t Exist « The Self-Taught Programmer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s