-
Hello there, I have the requirement to read a file that can come with or without header line. The problem I have is on how to specify at runtime if the fiel has or not the header row. Is there any Option that I can pass to the Reader that can help me in this situation? |
Beta Was this translation helpful? Give feedback.
Answered by
JoshClose
Dec 1, 2022
Replies: 1 comment
-
You can just test the first row. Make sure to specify the index in the mapping for when there isn't a header. void Main()
{
var s = new StringBuilder();
s.Append("Id,Name\r\n");
s.Append("1,one\r\n");
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
};
using (var reader = new StringReader(s.ToString()))
using (var csv = new CsvReader(reader, config))
{
csv.Context.RegisterClassMap<FooMap>();
csv.Read();
if (csv.GetField(0) == "Id")
{
csv.ReadHeader();
}
csv.GetRecords<Foo>().ToList().Dump();
}
}
private class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
private class FooMap : ClassMap<Foo>
{
public FooMap()
{
Map(m => m.Id).Index(0);
Map(m => m.Name).Index(1);
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
JoshClose
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can just test the first row.
Make sure to specify the index in the mapping for when there isn't a header.