'TextFieldParser ignoring header row C#
Reading in CSV files and the TextFieldParser skips the header row.
Any idea how to make certain the first row is skipped.
String[] Col3Value = new string[40];
TextFieldParser textFieldParser = new TextFieldParser(File1);
textFieldParser.TextFieldType = FieldType.Delimited;
textFieldParser.SetDelimiters(",");
{
{
string FileName = this.Variables.FileName.ToString();
{
while (!textFieldParser.EndOfData)
{
File1OutputBuffer.AddRow();
string[] values = textFieldParser.ReadFields();
for (int i = 0; i <= values.Length - 1; i++)
{
Col3Value[i] = values[i];
File1OutputBuffer.Column1 = Col3Value[0];
File1OutputBuffer.Column2 = Col3Value[1];
}
}
}
}
textFieldParser.Close();
}
Solution 1:[1]
You must manually skip first line.
Example from Parsing a CSV file using the TextFieldParser
using (TextFieldParser parser = new TextFieldParser(path))
{
// set the parser variables
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
bool firstLine = true;
while (!parser.EndOfData)
{
//Processing row
string[] fields = parser.ReadFields();
// get the column headers
if (firstLine)
{
firstLine = false;
continue;
}
}
}
Solution 2:[2]
Explicitly read the first line in an unparsed manner
if (!parser.EndOfData) {
parser.ReadLine();
}
while (!parser.EndOfData)
{
var fields = parser.ReadFields();
...
}
Solution 3:[3]
parser.LineNumber starts off as 1, so just continue after the first read.
while (!parser.EndOfData)
{
var fields = parser.ReadFields();
if (parser.LineNumber <= 2) continue;
...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Richard |
Solution 3 | Rob Sedgwick |