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 ?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With