Search code examples
c#csvcsvhelper

CsvHelper - Skip rows from csv file arbitrary rows


I have a csv file like this

'some lines to skip : line 1 to 7'
Name,Family,Mobile
'line nine: should be skipped'
'line ten: should be skipped'
A,B,1
C,D,2

How Can I skip first seven lines and third line with ShouldSkipRecord by RowIndex?
I've searched a lote but I did not find any solutions.

This is my codes

var options = new TypeConverterOptions { Formats = new[] { "dd/MM/yyyy HH:mm:ss" } };
using var reader = new StreamReader(@"C:\Users\Arash\Desktop\fault1.csv");
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
     ShouldSkipRecord = args =>
     {
        //some thing which show row index
     }
};
using var csv = new CsvReader(reader, config);
csv.Context.RegisterClassMap<FaultsModelMap>();
csv.Context.TypeConverterOptionsCache.AddOptions<DateTime>(options);
var records = csv.GetRecords<FaultsModel>();

Solution

  • Dear @JoshClose answered my question in the Github, I share the solution with developers who will be faced with same issue.

    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
        ShouldSkipRecord = args =>
        {
            var rawRow = args.Row.Parser.RawRow;
            return rawRow < 8 || rawRow == 9 || rawRow == 10;
        }
    };
    

    Please don't forget that line indices starts from 1 not 0