Categories
.net arrays c# csv

Reading CSV file and storing values into an array

414

I am trying to read a *.csv-file.

The *.csv-file consist of two columns separated by semicolon (“;“).

I am able to read the *.csv-file using StreamReader and able to separate each line by using the Split() function. I want to store each column into a separate array and then display it.

Is it possible to do that?

4

  • 2

    @Marc: unfortunately in non-english cultures (e.g. Italian) when you save an excel to CSV it uses ";" as separator… this has made CSV a non-standard imo 🙁

    – digEmAll

    Mar 12, 2011 at 14:22


  • 29

    I always read CSV as character-separated-values since people call files CSV even if they don’t use a comma as separator. And there are so many dialects with different quoting or escaping rules in practice that you can’t really talk of a standard even if in theory there is a RFC.

    Mar 12, 2011 at 14:31


  • 5

    CSV file extension name should now get change to DSV – Delimiter Separated Values File

    – Ambuj

    Sep 25, 2019 at 11:07

  • 2

    For all of the answers that simply split the string on the delimiter character, this is not the best way to go. There are more rules to the CSV format that this will not cover. It is best to use a 3rd party parser. More info- dotnetcoretutorials.com/2018/08/04/csv-parsing-in-net-core

    Apr 21, 2020 at 20:31

247

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

6

  • 7

    I like this option the best. I don’t have to worry about escape characters since the class is a CSV parser and not something being built manually.

    Oct 10, 2016 at 19:15

  • 28

    In case anyone runs into this and is wondering, you’ll need to include the reference to Microsoft.VisualBasic framework assembly as it is not typically referenced by default.

    – apokryfos

    Feb 21, 2017 at 15:45

  • 3

    I wish I had remembered this from my VB6 days, would have saved me a lot of time over the years. While some will rant about VB, I have no issue adding the dll & namespace to my code if it has value. This has A LOT of value.

    – Walter

    May 30, 2018 at 15:56

  • 3

    This solution is a homerun. very reliable parser from my experience.

    Mar 28, 2019 at 19:12

  • 4

    Why only in VB dll?

    – Mark Choi

    Dec 27, 2019 at 7:53

86

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

9

  • 16

    @ClayShannon .NET 1.1 ? I’m…very sorry for you.

    Jun 3, 2013 at 17:55

  • 6

    @contactmatt: I won’t disabuse you of that sentiment.

    Jun 3, 2013 at 19:01

  • 11

    I also want to point out that csv’s can be quoted… So using string.Split isn’t a viable option.

    – Alxandr

    Jul 9, 2013 at 10:48

  • 5

    I am getting: ‘System.Array’ does not contain a definition for ‘Split’ and no extension method ‘Split’ accepting a first argument of type ‘System.Array’ could be found (are you missing a using directive or an assembly reference?)

    – Kala J

    May 16, 2014 at 19:22

  • 4

    You are getting System.Array doesnt contain a definition because lines is an IEnumerable(string []) so line is basically a string array that has one element. Just change that to var csv = from line in lines select (line[0].Split(‘,’)).ToArray();

    Jun 13, 2014 at 22:27