Tuesday, June 07, 2005

Reading CSV files in C#

One can use ODBC to easily read a CSV (Comma Seperated Variables) files. Here is some example code that shows how: //using System.Data; //using System.Data.Odbc; // Set the Connection String //FOLDERNAME points to the folder where your test.csv file exists string connStr = @"Driver={Microsoft Text Driver (*.txt; *.csv)};" + "Dbq=" + FOLDERNAME + ";"; // Get all Table Names OdbcConnection conn = new OdbcConnection(connStr); // Read it //test.csv is the file that is being read OdbcDataAdapter da = new OdbcDataAdapter("select * from [test.csv]", conn); try { DataSet ds = new DataSet(); da.Fill(ds); //where dataGrid is a Windows.Forms.DataGrid on the form dataGrid.DataSource = ds.Tables[0]; MessageBox.Show(ds.Tables[0].Rows.Count.ToString() + " row(s) returned"); } catch (OdbcException ex) { string msg = ex.Message; string errors = ""; foreach (OdbcError err in ex.Errors) { errors += err.Message; } MessageBox.Show(errors, msg); }

No comments: