Getting error when trying to store csv file contents into a C# Dictionary using CsvHelper

134 Views Asked by At

I would like to use C# and the CsvHelper library to read a csv file and store its contents into a Dictionary. Consider the Test.csv file with the following content:

One,1
Two,2
Three,3
Four,4
Five,5

What I need is to put this csv information in a Dictionary<string, int> where the key is the first column and the value is the second column. I tried to implement the solution presented in the post Mapping to a Dictionary, but I'm getting a NullReferenceException in the foreach block because none data was being allocated into dict variable:

using System;
using System.IO;
using System.Globalization;
using System.Collections.Generic;

using CsvHelper;

namespace TestCsvHelper
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var reader = new StreamReader("C:\\Test.csv"))
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                csv.Read();
                var dict = csv.GetRecord<dynamic>() as IDictionary<string, int>;

                foreach (string key in dict.Keys)
                {
                    Console.WriteLine("Key: {0}, Value: {1}", key, dict[key]);
                }
            }
        }
    }
}

Could somebody help me showing what I'm doing wrong?

Best regards,

Fabiano

1

There are 1 best solutions below

0
On BEST ANSWER

If at all casting to Dictionary works, csv.GetRecord will only give you one record. I tried reading with csv.GetRecords and converting it's response to Dictionary. Check below code if this is what you expect:

  static void Main(string[] args)
        {
            using (var reader = new StreamReader("c:\\Test.csv"))
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                csv.Configuration.HasHeaderRecord = false; //since csv does not have headers
                var dict = csv.GetRecords<dynamic>().ToDictionary(lm=>lm.Field1,lm=>lm.Field2);

                foreach (var key in dict.Keys)
                {
                    Console.WriteLine("Key: {0}, Value: {1}", key, dict[key]);
                }
            }
            Console.ReadLine();
       }