Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextFieldParser ignoring header row C#

Tags:

c#

csv

ssis

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();
}
like image 942
john Avatar asked Feb 01 '17 09:02

john


3 Answers

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;
        }           
    }
}
like image 132
BWA Avatar answered Nov 20 '22 00:11

BWA


Explicitly read the first line in an unparsed manner

if (!parser.EndOfData) {
    parser.ReadLine();
}

while (!parser.EndOfData)
{
    var fields = parser.ReadFields();
    ...
}
like image 24
Richard Avatar answered Nov 19 '22 22:11

Richard


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;
    
    ...
}
like image 1
Rob Sedgwick Avatar answered Nov 19 '22 22:11

Rob Sedgwick