I am trying to use TextFieldParser with c# to parse a csv file and get the values of rows for specific columns.
For example a csv with..
Name,Age,Color,Sport
Tom,24,Blue,Football
Dick,21,Red,Hockey
Jane,19,Green,Basketball
string fullpath = "C:\myfile.csv"
using (TextFieldParser parser = new TextFieldParser(fullPath))
{
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
// Processing row
string[] fields = parser.ReadFields();
int sportcount = 0;
for (int i = 0; i < fields.Length; ++i)
{
string column = fields[i];
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
if (column.Contains("Sport"))
{
Console.WriteLine("Found Sport at {0}", i);
sportcount = i;
}
}
string sportCol = fields[sportCount];
// if that column contains a value
if (!(sportCol.Equals("")) {
// ignore the column header row
if (parser.LineNumber > 2) {
if (sportCol.Equals("Football")) {
Console.WriteLine("Found somebody playing football");
}
}
}
}
}
So idealy i'd like a list or array containing all the sports of those in the csv file. So it should contain (Football, Hockey, Basketball). Bearing in mind, the actual csv file has hundreds of columns and thousands of rows.
Update: I've update the above to something that is working for me. By assigning i to a variable when it finds a 'Sport' column, then I can search for that columns value down through the csv file.