StreamReader with tab delimited text file

时光总嘲笑我的痴心妄想 提交于 2019-12-06 06:39:33

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.

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'));
    }
}

If you have only tab characters you can use Split('\t'), but if the tabs are white spaces you might want to use regular expressions

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