CSVHelper to skip record before header

笑着哭i 提交于 2021-02-19 05:25:38

问题


I have data in a file in following format.

HEADER|ReportItem Name: Margin Ri.....
Account Id/Margin Id|Account Name|Ba...... // the row with headers
Data row 1
Data row 2
TRAILER|Record Count: 2

This is throwing an error - I believe due to fact there is a that row before the actual reader row.

using (var textReader = File.OpenText(path))
{
    var csv = new CsvReader(textReader);
    csv.Configuration.RegisterClassMap<GsClassMap>();
    csv.Configuration.TrimOptions = TrimOptions.Trim;
    csv.Configuration.MissingFieldFound = null;
    csv.Configuration.Delimiter = "|";
    csv.Configuration.HasHeaderRecord = true;
    csv.Configuration.ShouldSkipRecord = (x) => x[0].StartsWith("HEADER");
    csv.Configuration.ShouldSkipRecord = (x) => x[0].StartsWith("TRAILER");
    return csv.GetRecords<GsSma>().ToList();
}

This is throwing an error - I believe due to fact there is a that row before the actual reader row.

Header matching ['Account Id/Margin Id'] names at index 0 was not found.

How can I set this up to read the file correctly?


回答1:


When setting ShouldSkipRecord the second time, you're overwriting the first instance. You just need to do this instead.

csv.Configuration.ShouldSkipRecord = row => row[0].StartsWith("HEADER") || row[0].StartsWith("TRAILER");


来源:https://stackoverflow.com/questions/51044949/csvhelper-to-skip-record-before-header

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!