Search code examples
c#csvhelper

CsvHelper isn't parsing csv


I'm trying to use CsvHelper to parse a csv file and get an array of class objects. But I can't get any results from CsvReader. What am I doing wrong?

TextReader reader = File.OpenText("test.csv");
string stringResult=reader.ReadToEnd(); //this works

var csvReader = new CsvReader(reader);
TestCsvEntity[] resultReader = csvReader.GetRecords<TestCsvEntity>().ToArray(); //but this is empty

My test.csv file is just this:

RowNumber,Value
1,a
2,b
3,c

And my class object is

public class TestCsvEntity
{
    public int RowNumber { get; set; }
    public string Value { get; set; }
}

Solution

  • If this is in your code, remove it:

    string stringResult=reader.ReadToEnd(); //this works
    

    It is likely reading to the end of the stream and then you are passing a reader to the CSVHelper that is at the last position in the stream. You want to pass CSVHelper a stream that is at the start position.

    Try this for debugging:

    TextReader reader = File.OpenText("test.csv");
    
    Console.WriteLine("Stream Length:" + reader.BaseStream.Length);
    Console.WriteLine("Stream Position before ReadToEnd(): " + reader.BaseStream.Position);
    
    string stringResult=reader.ReadToEnd(); //this works
    
    Console.WriteLine("Stream Position after ReadToEnd(): " + reader.BaseStream.Position);