I am using CsvHelper to write a csv file with multiple header lines, at different positions (the headers have the some number of columns, but different names). The number of rows after each header is different.
Is there any possibility to use CsvHelper to find/iterate over the different header lines inside the csv file (maybe by searching by the name or part of the names for the header columns) and read iteratively the records after each header?
You will have to do this manually, read line by line and decide what you are going to do.
Example to you start:
CSV File:
Test1, Test2, Test3
A,1,foo
TestA, TestB, Test3
B,07a0fca2-1b1c-4e44-b1be-c2b05da5afc7,bar
void Main()
{
using (var reader = new StreamReader("path\\to\\file.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Configuration.HasHeaderRecord = false;
csv.Configuration.RegisterClassMap<FooMap>();
csv.Configuration.RegisterClassMap<BarMap>();
var fooRecords = new List<Foo>();
var barRecords = new List<Bar>();
while (csv.Read())
{
switch (csv.GetField(0))
{
case "A": // Or "Test1"
...
break;
case "B": // Or "TestA"
...
break;
default:
throw new InvalidOperationException("Unknown record type.");
}
}
}
}
Example and documentation: Reading Multiple Record Types