How to properly read columns from text file

StackTrace picture StackTrace · Jul 16, 2012 · Viewed 7.2k times · Source

Im trying to read data from a text file and loading it into a dataset but the different columns as in the image below are coming as just one long column. I want to return the data as 7 columns (in the same way as its appearing in the image below).

This is the code am using,

public DataSet LoadTxtFile(int numberOfRows)
    {
        DataSet ds = new DataSet();
        //try
        //{
            // Creates and opens an ODBC connection
            string strConnString = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + this.dirCSV.Trim() + ";Extensions=asc,csv,tab,txt;Persist Security Info=False";
            string sql_select;
            OdbcConnection conn;
            conn = new OdbcConnection(strConnString.Trim());
            conn.Open();

            //Creates the select command text
            if (numberOfRows == -1)
            {
                sql_select = "select * from [" + this.FileNevCSV.Trim() + "]";
            }
            else
            {
                sql_select = "select top " + numberOfRows + " * from [" + this.FileNevCSV.Trim() + "]";
            }

            //Creates the data adapter
            OdbcDataAdapter obj_oledb_da = new OdbcDataAdapter(sql_select, conn);

            //Fills dataset with the records from CSV file
            obj_oledb_da.Fill(ds, "csv");

            //closes the connection
            conn.Close();
        //}
        //catch (Exception e) //Error
        //{
            //MessageBox.Show(e.Message, "Error - LoadCSV",MessageBoxButtons.OK,MessageBoxIcon.Error);
        //}
        return ds;
    }

Text File Sample Data

Answer

Alberto De Caro picture Alberto De Caro · Jul 16, 2012

I usually adopt a trivial solution, i.e. I access the file, I read all lines, in a loop I split the line string, create and populate a new datarow, and finally I add the data row to the datatable:

string[] records = File.ReadAllLines(path);
foreach(string record in records)
{
  DataRow r = myDataTable.NewRow();
  string[] fields = record.Split('\t');
  /* Parse each field into the corresponding r column
   * ....
   */
  myDataTable.rows.Add(r);
}

I have also found solutions regarding how to access CSV files with OleDb connections, and schema information files. I have never used this approach.

References: