Kareem Musa
0
Q:

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;
 }

// or
var dict = File.ReadLines(pathToCsvFile).Select(line => line.Split(';')).ToDictionary(line => line[0], line => line[1]);
0
String csv = String.Join(
    Environment.NewLine,
    data.Select(d => $"{d.Key};{d.Value};")
);
System.IO.File.WriteAllText(pathToCsv, csv);
0

New to Communities?

Join the community