Reputation: 13
I am new to C# and hoping you can help me. I have text file with data mad of rows and the columns are separated by tabs. See example below. My question: how can read the data from just column three.
739492 3 600 3 600
739493 20 4000 3 600
739494 3 600 3 600
739495 20 4000 3 600
739496 3 600 3 600
739497 20 4000 3 600
My current code reads the full line:
private void btnRead_Click(object sender, EventArgs e)
{
string assemblyName = Assembly.GetExecutingAssembly().Location;
string assemblyDirectory = Path.GetDirectoryName(assemblyName);
m_readFile = new StreamReader (assemblyDirectory + @"\" + "MyDataFile.txt");
int counter = 1;
string line;
while ((line = m_readFile.ReadLine()) != null)
{
MessageBox.Show(line);
counter++;
}
m_readFile.Close();
}
Upvotes: 1
Views: 4195
Reputation: 7213
You can do something like this:
private void btnRead_Click(object sender, EventArgs e)
{
string assemblyName = Assembly.GetExecutingAssembly().Location;
string assemblyDirectory = Path.GetDirectoryName(assemblyName);
m_readFile = new StreamReader (assemblyDirectory + @"\" + "MyDataFile.txt");
int counter = 1;
string line;
while ((line = m_readFile.ReadLine()) != null)
{
string col = line.Split(' ')[2];
MessageBox.Show(line);
counter++;
}
m_readFile.Close();
}
If your columns in text file are separated by TAB you need to use:
string col = line.Split('\t')[2];
Hope it helps.
Upvotes: 0
Reputation: 34170
while ((line = m_readFile.ReadLine()) != null)
{
string[] columns = line.Split(',');
//Now you can access the 3rd column of each line with column[2]
counter++;
}
Upvotes: 1
Reputation: 17589
I would suggest using CsvHelper (http://joshclose.github.io/CsvHelper/)
var csv = new CsvReader( textReader );
while( csv.Read() )
{
var intField = csv.GetField<int>( 2 ); // index is 0 based
}
Upvotes: 0