Connect to a CSV file using ODBC [C#]

I mentioned that it’s easy to work with CSV/XML files using ODBC, ADO.NET, etc. Here is some sample C# code that works with CSV files using ODBC (using System.Data.Odbc):

string strConn = @"Driver={Microsoft Text Driver (*.txt; *.csv)};" +
  "Dbq=C:;Extensions=csv,txt";

try
{
  OdbcConnection objCSV = new OdbcConnection(strConn);
  objCSV.Open();

  OdbcCommand oCmd = new OdbcCommand("select column1,column2 " +
    "from THECSVFILE.CSV", objCSV);
  OdbcDataReader oDR = oCmd.ExecuteReader();

  while (oDR.read())
  {
    // Do something
  }
  oDR.Close();
  oCmd.Dispose();
  objCSV.Close();
}
catch {}

In the Connection String, DBQ only points to the directory which contains the CSV files you want to work with. Use the name of the CSV file in the SQL Statement itself, as in the code above.

Simple?

  • Share/Bookmark

5 Comments

ChrisOctober 27th, 2004 at 9:59 pm

Great example – found it ignores the first line – must assume field names – what is required to read first line?

MikhailOctober 27th, 2004 at 11:55 pm

Hi Chris: I think you’ll need to read that line manually.

BillOctober 28th, 2005 at 7:13 pm

That last post mangled the URL, so I’ll try something else.

See the connection strings for “Text” at http://www.connectionstrings.com/
—- ODBC —-
“Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=c:\txtFilesFolder\;Extensions=asc,csv,tab,txt;”
—- OLEDB —-
“Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\txtFilesFolder\;Extended Properties=”“text;HDR=Yes;FMT=Delimited”“”
(“HDR=Yes;” indicates that the first row contains columnnames, not data)

IanMay 19th, 2009 at 8:46 pm

Nice example. Note that there should be a capital R on oDR.read().
Also a finally block to close the file, or alternatively use the ‘using’ construct to open the connection.

Leave a comment

Your comment