CSV to DataTable

Converting Microsoft Excel CSV to .Net DataTable:
After casually browsing the net for some good examples, everything I came across was too bulky or over-kill for what I needed this code for, so I decided to write my own.

The following code snippet is tested and works with .Net 2.0 or later. Please note “handleError()” method which is not defined in code below. This is simply generic static method accepting string and exception types to handle all exceptions in your application in a uniform manner.

The nice thing about this code compared to some other examples you may come across in your searches is that it works stand-alone without any external references or potentially buggy usage/constructors such as OleDB Jet provider.

It’s clean, concise, and to the point. Use it wisely. 😉

private DataTable MyCSVtoDT(string FileNameWithPath)
    try {
        bool HeaderColumnsAdded = false;
        DataTable dt = new DataTable();
        StreamReader reader = File.OpenText(FileNameWithPath);
        string line = reader.ReadLine();
        while ((line != null)) {
            int colcounter = 0;
            DataRow row = dt.NewRow();
            foreach (string colvalue in line.Split(“,”)) {
                if (HeaderColumnsAdded == false) {
                row(colcounter) = colvalue;
                colcounter += 1;
            HeaderColumnsAdded = true;
            line = reader.ReadLine();
        return dt;
    catch (Exception ex0) {
        handleError(ex0, “Ex0::MyCSVtoDT”);
        throw new Exception(ex0.Message, ex0.InnerException);
        return null;

About Ronnie Diaz

Ronnie Diaz is an enterprise software engineer responsible for front-end and back-end development for companies in many industries. Heavily involved in cloud development, online retail, e-commerce and electronic ordering, fulfillment and customer relational systems.

Posted on March 2, 2010, in Programming & Development. Bookmark the permalink. 1 Comment.

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: