Thursday, 12 March 2015

Reading CSV file and storing values into an array


using System.IO;

static void Main(string[] args)
{
    var reader = new StreamReader(File.OpenRead(@"C:\test.csv"));
    List<string> listA = new List<string>();
    List<string> listB = new List<string>();
    while (!reader.EndOfStream)
    {
        var line = reader.ReadLine();
        var values = line.Split(';');

        listA.Add(values[0]);
        listB.Add(values[1]);
    }
}

LINQ way:
var lines = File.ReadAllLines("test.txt").Select(a => a.Split(';'));
var csv = from line in lines
          select (from piece in line
                  select piece);

No comments:

Post a Comment