StreamReader with tab delimited text file

我怕爱的太早我们不能终老 提交于 2019-12-12 10:08:34

问题


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?


回答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.




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



回答3:


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



来源:https://stackoverflow.com/questions/14954437/streamreader-with-tab-delimited-text-file

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