Skip to content

How to read a CSV that might or might not have Header row #2094

Answered by JoshClose
middiu asked this question in Q&A
Discussion options

You must be logged in to vote

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 N…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by JoshClose
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants