Click here to Skip to main content
15,888,239 members
Articles / Programming Languages / C#
Tip/Trick

Poor Man's Method of Reading CSV File into DataTable

Rate me:
Please Sign up or sign in to vote.
4.79/5 (9 votes)
10 Jul 2015CPOL 23.6K   11   5
This tip contains a snippet that reads a comma-separated-values file into a DataTable.

Introduction

Sometimes, you just need a quick way to read a CSV file and process the contents. There are many ways to do it, some of them using third-party tools, opensource libraries, regular expressions and the like. This tip provides a simple, native .NET method to read a CSV file into a System.Data.DataTable object. We won't focus on validation, checking if the file exists, parsing the content or anything like that and will assume that we're working with a well-formed .CSV file. As always, good error handling is king, but it isn't the objective with this tip.

Using the Code

The OpenCsvFileAsDataTable() method is listed below:

C#
public DataTable OpenCsvFileAsDataTable(string fileName, bool firstLineIsHeader)
{
    DataTable result = new DataTable();
    System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);
    
    // The table name is the actual name of the file.
    string tableName = fileInfo.Name;
    
    // Get the folder name in which the file is. This will be part of the 
    // connection string.
    string folderName = fileInfo.DirectoryName;
    string connectionString = "Provider=Microsoft.Jet.OleDb.4.0;" +
                              "Data Source=" + folderName + ";" +
                              "Extended Properties=\"Text;" + 
                              "HDR=" + (firstLineIsHeader ? "Yes" : "No") + ";" + 
                              "FMT=Delimited\"";
    
    using (System.Data.OleDb.OleDbConnection connection =
        new System.Data.OleDb.OleDbConnection(connectionString))
    {
        // Open the connection 
        connection.Open();
            
        // Set up the adapter and query the table.
        string sqlStatement = "SELECT * FROM " + tableName;
        using (System.Data.OleDb.OleDbDataAdapter adapter =
            new System.Data.OleDb.OleDbDataAdapter(sqlStatement, connection))
        {
            result = new DataTable(tableName);
            adapter.Fill(result);
        }
    }

    return result;
}

Points of Interest

The directory in which the file is will be opened as a "database". Each of the CSV files in the directory can be queried as if they're a table.

It might not be the absolute best way of doing this, but it is a reasonably good, functional, poor-man's way to quickly read and consume the content of a CSV file. What is great about it is that you don't need much to get it working.

History

  • 10th July, 2015 - Initial tip

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Independent Contractor
Australia Australia
I started off as a VB3 programmer after completing a COBOL course in the mid 90's. After learning COBOL, VB was a breath of fresh air and a lot more "fun" to work with. My big break came when I landed on a big VB5/6 project in 1998. I worked under a couple of good guys and learnt a lot from them on the project.

When .NET was released, I started out as a VB.NET developer working on various Windows Forms as well as ASP.NET Projects. It didn't take long to make the transition to C# and today I'm more comfortable with C# than VB.NET. I've also had the fortune to work with SharePoint 2003-2013 quite a bit and love it as a platform.

Programming is an awesome and FUN challenge that I still enjoy after almost 20 years in the field, and I constantly strive to become better at it.

Comments and Discussions

 
SuggestionDeprecation of Jet Pin
darkliahos11-Jul-15 0:14
darkliahos11-Jul-15 0:14 
GeneralRe: Deprecation of Jet Pin
Steven Oberholzer12-Jul-15 13:08
professionalSteven Oberholzer12-Jul-15 13:08 
Questionet tu TextFieldParser? Pin
AFell210-Jul-15 5:37
AFell210-Jul-15 5:37 
AnswerRe: et tu TextFieldParser? Pin
Steven Oberholzer12-Jul-15 18:14
professionalSteven Oberholzer12-Jul-15 18:14 
GeneralMy vote of 5 Pin
newton.saber10-Jul-15 4:30
newton.saber10-Jul-15 4:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.