How to properly read columns from text file

2019-07-17 02:45发布

问题:

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;
    }

回答1:

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:

  • File.ReadAllLInes().
  • String.Split().
  • Stackoverflow related question with OleDb connection.
  • MSDN Schema Information File.