StreamReader with tab delimited text file

22,270

Solution 1

You can try this:

        DataTable table = new DataTable();
        table.Columns.Add("col1");
        table.Columns.Add("col2");
        table.Columns.Add("col3");

        var lines = File.ReadAllLines(@"Data.txt").ToList();
        lines.ForEach(line => table.Rows.Add(line.Split((char)9)));

I presumed that rows are delimited by newline (if that's the case ReadAllLines method can be used). Number 9 is the ASCII value for horizontal tab character and it is used for splitting the line. ForEach is a method that can be used on generic lists, it is there instead of the foreach loop.

Solution 2

The escape character for a tab in C# is \t, so to read a file and split each line on a tab I'd use

var path = "path to file";
using (StreamReader sr = new StreamReader(path))
{
    while (sr.Peek() >= 0)
    {
        //Reads the line, splits on tab and adds the components to the table
        table.Rows.Add(sr.ReadLine().Split('\t'));
    }
}
Share:
22,270
Stuart
Author by

Stuart

BY DAY: Software Engineer - .Net C# (Web forms and MVC), HTML5, CSS3, JQuery, Angular, SQL. BY NIGHT: Husband, Father and Cook! FOR FUN: My Daughter, My Wife, Gardening, Cooking, DIY. General hands on type stuff!

Updated on July 09, 2022

Comments

  • Stuart
    Stuart almost 2 years

    I have a similar requirement to this post... Populate Gridview at runtime using textfile

    Where I want to read a text file with StreamReader and populate a DataTable with the data in the file, however I'm not sure how to implement a split() with a tab.

    Could anybody point me in the right direction, please?

    • Neha
      Neha about 11 years
      sr.ReadLine().Split("\t"); used in vb not sure about this.
    • Ivan Golović
      Ivan Golović about 11 years
      Fields are delimited by tab, how are rows delimited? By newline?
    • Stuart
      Stuart about 11 years
      new rows are new lines. this is a fairly simple and standard edi file layout that i am trying to read and display to the end user.
  • Stuart
    Stuart about 11 years
    Thank you, I will try this out today and check back on how I get on. Much appreciated!