Friday, May 4, 2007

Reading a .csv or a comma-delimited .txt file using SQL

Sample code for Reading a .csv or a comma-delimited .txt file using SQL:

Below:
1) StoragePath is the absolute path to the .csv file.
2) Substitute MyFileName.csv with your file name.

using System.Data.Odbc;
public void ReadData()
{
string StoragePath = @"c:\test";
string strSQL = "Select * from MyFileName.csv";
OdbcConnection conn = new OdbcConnection(
@"Driver={Microsoft Text Driver (*.txt; *.csv)};DBQ="+StoragePath);


conn.Open();

OdbcDataAdapter da = new OdbcDataAdapter(strSQL, conn);

DataSet ds = new DataSet();

da.Fill(ds);

conn.Close();
}