-
I have tried to read multiple datasets (with different headers) as explained in the on the page Reading Multiple Data Sets This works fine. The problem I have is that my source files does not have a blank line between the first datatset and the second data set. Using the sample file from the above link works fine:
but if the blank line is not there the code doesn't work:
So my question is if anyone here have any clever suggestions as to how to read the file with two datasets but no blank lines between the data sets? I guess one way would be to assume the first dataset is always of a specific length, but I'm curious if better ideas exists? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You just need to test if the line is a header. Here is an example using the data you provided. void Main()
{
var s = new StringBuilder();
s.Append("FooId,Name\r\n");
s.Append("1,one\r\n");
s.Append("BarId,Name\r\n");
s.Append("07a0fca2-1b1c-4e44-b1be-c2b05da5afc7,bar\r\n");
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
};
using (var reader = new StringReader(s.ToString()))
using (var csv = new CsvReader(reader, config))
{
var foos = new List<Foo>();
var bars = new List<Bar>();
while (csv.Read())
{
if (csv[0] == "FooId" || csv[0] == "BarId")
{
csv.ReadHeader();
continue;
}
switch (csv.HeaderRecord[0])
{
case "FooId":
foos.Add(csv.GetRecord<Foo>());
break;
case "BarId":
bars.Add(csv.GetRecord<Bar>());
break;
default:
throw new InvalidOperationException("Unknown record type.");
}
}
foos.Dump();
bars.Dump();
}
}
private class Foo
{
public int FooId { get; set; }
public string Name { get; set; }
}
private class Bar
{
public Guid BarId { get; set; }
public string Name { get; set; }
} |
Beta Was this translation helpful? Give feedback.
You just need to test if the line is a header. Here is an example using the data you provided.