Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Poor Man's Method of Reading CSV File into DataTable

0.00/5 (No votes)
10 Jul 2015 1  
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:

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here