c# load csv into dictionary code example
Example 1: how to read a csv file and create a dictionary in c#
private Dictionary<string, string> ReadCsvFile(string pathToCsvFile)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
using (var reader = new StreamReader(pathToCsvFile))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line == null) continue;
var values = line.Split(';');
dictionary.Add(values[0],values[1]);
}
}
return dictionary;
}
var dict = File.ReadLines(pathToCsvFile).Select(line => line.Split(';')).ToDictionary(line => line[0], line => line[1]);
Example 2: how to save a dictionary as a csv file in c#
String csv = String.Join(
Environment.NewLine,
data.Select(d => $"{d.Key};{d.Value};")
);
System.IO.File.WriteAllText(pathToCsv, csv);