C# 带有制表符分隔文本文件的 StreamReader

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14954437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:32:04  来源:igfitidea点击:

StreamReader with tab delimited text file

c#asp.netsplitstreamreadertab-delimited-text

提问by Stuart

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

我对这篇文章有类似的要求... 在运行时使用文本文件填充 Gridview

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

我想在哪里读取文本文件StreamReaderDataTable使用文件中的数据填充 a ,但是我不确定如何split()使用选项卡实现 a 。

Could anybody point me in the right direction, please?

有人能指出我正确的方向吗?

采纳答案by Ivan G

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 ReadAllLinesmethod can be used). Number 9 is the ASCII value for horizontal tab character and it is used for splitting the line. ForEachis a method that can be used on generic lists, it is there instead of the foreachloop.

我假设行由换行符分隔(如果ReadAllLines可以使用这种情况方法)。数字 9 是水平制表符的 ASCII 值,用于分割行。ForEach是一种可用于泛型列表的方法,它在那里而不是foreach循环。

回答by Benny

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

如果您只有制表符,您可以使用 Split('\t'),但如果制表符是空格,您可能需要使用正则表达式

回答by Martin McGirk

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

C# 中选项卡的转义字符是\t,因此要读取文件并在我使用的选项卡上拆分每一行

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