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
StreamReader with tab delimited text file
提问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 StreamReader
and populate a DataTable
with the data in the file, however I'm not sure how to implement a split()
with a tab.
我想在哪里读取文本文件StreamReader
并DataTable
使用文件中的数据填充 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 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.
我假设行由换行符分隔(如果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'));
}
}