Reading CSV file and storing values into an array Reading CSV file and storing values into an array arrays arrays

Reading CSV file and storing values into an array


You can do it like this:

using System.IO;static void Main(string[] args){    using(var reader = new StreamReader(@"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]);        }    }}


My favourite CSV parser is one built into .NET library. This is a hidden treasure inside Microsoft.VisualBasic namespace.Below is a sample code:

using Microsoft.VisualBasic.FileIO;var path = @"C:\Person.csv"; // Habeeb, "Dubai Media City, Dubai"using (TextFieldParser csvParser = new TextFieldParser(path)){ csvParser.CommentTokens = new string[] { "#" }; csvParser.SetDelimiters(new string[] { "," }); csvParser.HasFieldsEnclosedInQuotes = true; // Skip the row with the column names csvParser.ReadLine(); while (!csvParser.EndOfData) {  // Read current line fields, pointer moves to the next line.  string[] fields = csvParser.ReadFields();  string Name = fields[0];  string Address = fields[1]; }}

Remember to add reference to Microsoft.VisualBasic

More details about the parser is given here: http://codeskaters.blogspot.ae/2015/11/c-easiest-csv-parser-built-in-net.html


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

^^Wrong - Edit by Nick

It appears the original answerer was attempting to populate csv with a 2 dimensional array - an array containing arrays. Each item in the first array contains an array representing that line number with each item in the nested array containing the data for that specific column.

var csv = from line in lines          select (line.Split(',')).ToArray();