Fill in the data table from a text file

I have this block of code that reads a text file [Tab delimited] and returns a data table. But the problem is that it treats the first line of the file or record as a header and displays the remaining lines as records, which subtract the number of records by -1, so now I want the code to read the entire contents 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 the lines that depend on it, dt returns nothing.

how can i solve it?

+4
source share
2 answers

If you know that there is no heading, I assume that you also do not know the names of the columns, right? 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); } 
+5
source
 DataTable dt = new DataTable(); var lines = File.ReadAllLines(strPath).ToList(); dt.Columns.AddRange(lines.First().Split(new char[] { '\t' }).Select(col => new DataColumn(col)).ToArray()); lines.RemoveAt(0); lines.Select(x => x.Split(new char[] { '\t' })).ToList().ForEach(row => dt.Rows.Add(row)); 

Use this for test data.

 List<string> lines = new List<string>(); lines.Add("Col1\tCol2\tCol3"); lines.Add("aaa\tbbb\tccc"); 
+3
source

Source: https://habr.com/ru/post/1446903/


All Articles