JoshClose / CsvHelper

Library to help reading and writing CSV files
http://joshclose.github.io/CsvHelper/
Other
4.63k stars 1.05k forks source link

Skip rows from csv file arbitrary rows #2218

Closed zandiarash closed 6 months ago

zandiarash commented 6 months ago

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, 9th and 10th 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>();
JoshClose commented 6 months ago

If you want to skip 7 lines, you could do it in the stream before CsvHelper gets involved.

Otherwise you can use the RawRow to skip file lines. Row is the logical CSV row since a CSV row could have line breaks in it.

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

and third line

I'm not sure what you mean by that.

zandiarash commented 6 months ago

Sorry, I've edited my question. @JoshClose

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

args gives you the row to examine so you get get fields from it to test if you want to skip also.

zandiarash commented 6 months ago

Wow, That amazingly works, you are the best dear @JoshClose ❤️