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?
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
来源:https://stackoverflow.com/questions/14954437/streamreader-with-tab-delimited-text-file