Search code examples
.net-corecsvhelper

Why does not 'while(csv.Read())' work two / three times in CsvHelper?


I use the CsvHelper and I have the problem, I want to go over the rows as much as I have headers(columns) in a file and in every step does some specific logic in the while section. However, after the first circle, I can't go into the while and I don't have any idea how to fix it or how to maybe refresh the reader rows counter?

using (var reader = new StreamReader(file))
{
  var config = new CsvConfiguration(CultureInfo.InvariantCulture)
  {
    Delimiter = ";",
  };

  using (var csv = new CsvReader(reader, config))
  {
    for (var col = 1; col < headers.Length; col++)
    {
      while (csv.Read())
      {
        //do some logic
      }
    }
  }
}

have anyone an idea,


Solution

  • I believe you should switch your for and while statements. You need to read the row first and then loop through the columns.

    void Main()
    {
        using (var reader = new StringReader("Id,Name\n1,One\n2,Two"))
        using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
        {
            csv.Read();
            csv.ReadHeader();
            var headers = csv.HeaderRecord;
            
            while (csv.Read())
            {
                for (var col = 0; col < headers.Length; col++)
                {
                    Console.WriteLine(csv.GetField(col));               
                }
                Console.WriteLine();
            }
        }
    }
    
    public class Foo
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }