Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill a Data table from a text file

Tags:

c#

file

datatable

I have this block of code which reads a text file [Tab delimited] and return a data table. But the problem is that it treat the first line of the file or record as the header and display the remaining lines as records which subtract the number of record by - 1 so now i want the code to read all the content of the file as records.

here is the code:

streamReader reader = new streamReader (filePath);
string line = reader.readLine();
Datatable dt = new Datatable ();
DataRow row;
string[] value = line.Split('\t');

foreach(string dc in value)
{
 dt.columns.add(New DataColumn(dc));
}

while(!reader.endofStream)
 {
  value = reader.ReadLine().split('\t');

  if (value.Length == dt.Columns.Count)
 {
  row = dt.NewRow();
  row.ItemArray = value;
  dt.Rows.Add(row);
 }

 }

 return dt;

When i try to remove

foreach(string dc in value)
{
 dt.columns.add(New DataColumn(dc));
}

and all lines code that depend on it , the dt return nothing.

how can i solve it ?

like image 901
Djama Avatar asked Feb 18 '23 11:02

Djama


1 Answers

If you know that the there's no header, i assume that you don't know the name of the columns neither, do you? Then you need to add "anonymous" columns instead:

DataTable dt = new DataTable();
while (reader.Peek() >= 0)
{
    string line = reader.ReadLine();
    string[] fields = line.Split('\t');
    if (dt.Columns.Count == 0)
    {
        foreach (string field in fields)
        {
            // will add default names like "Column1", "Column2", and so on
            dt.Columns.Add(); 
        }
    }
    dt.Rows.Add(fields);
}
like image 182
Tim Schmelter Avatar answered Mar 02 '23 15:03

Tim Schmelter