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?


Great example – found it ignores the first line – must assume field names – what is required to read first line?
Hi Chris: I think you’ll need to read that line manually.
Chris,
Try using:
;HDR=No
http://msdn.microsoft.com/archive/default.asp?url=/archive/en-us/dnaraccessdev/html/ODC_MicrosoftOfficeDeveloperForumConnectionStringParametersinMicrosoftAccess.asp
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)
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.