The Self-Taught Programmer

Recipes from real-world experience with asp.net.

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

with one comment

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;
}
Advertisements

Written by Jim McMullen

October 10, 2011 at 1:33 pm

Posted in How-To

Tagged with

One Response

Subscribe to comments with RSS.

  1. […] have uploaded data into a DataTable (perhaps from a CSV file – see How To Parse a CSV File Into a DataTable for Use In Your Code) and now you need to retreive the data from the […]


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 )

Google+ photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s

%d bloggers like this: