How to properly read columns from text file

回眸只為那壹抹淺笑 提交于 2019-12-12 21:04:29

问题


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.


来源:https://stackoverflow.com/questions/11499893/how-to-properly-read-columns-from-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!