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