I´ve got a text file with tabulator separated data. What I need in my C# application is that I read one line from the text file and save them to an array, separate them at the each \t
. Then I do the same thing with the next row.
My code:
StreamReader sr = new StreamReader(dlg.FileName);
string s = sr.ReadLine();
Now, I already tried to write the line into an array but that doesn´t work. Does anyone one how to manage this?
Use the Split method to create an Array of the line
string[] parts = s.Split('\t');
See Documentation on Split() here
foreach (string line in System.IO.File.ReadAllLines(dlg.FileName))
{
var myArray = line.Split('\t');
}
s.Split('\t')
will split your string by the tabulator character, and create a string[]
with appropriate length.
Ammending your example code:
StreamReader sr = new StreamReader(dlg.FileName);
string s = sr.ReadLine();
var items = s.Split('\t');
In the end, items contains an array of strings that represent the characters between the tabs. The tabs are not included in the array. The array may contain empty elements (for the case of two consecutive tabs).
Use the String.Split()
method: http://msdn.microsoft.com/en-us/library/b873y76a.aspx
StreamReader reader = new StreamReader("input.txt");
string[] content = reader.ReadToEnd().Replace("\n","").Split('\t');
if you want to keep New Line's than
string[] content = reader.ReadToEnd().Split('\t');
In the example below, items
will be a String[]
containing each line of text's values. It will be overwritten with each iteration so you'll want to do something with it inside the loop. Save it to a larger collection, write it to a file, etc...
StreamReader sr = new StreamReader(dlg.FileName);
while (sr.Peek() >= 0) {
var line = sr.ReadLine();
var items = line.Split(new Char[] { '\t' });
}
If the file contains only one line, then use:
string[] myArray = s.Split('\t');