HOWTO · Csharp

How to Read a CSV File and Store Its Values Into an Array in C#

This how-to article shows different methods to read a CSV file and store its values into an array in C#. It introduces methods like OpenRead(), ReadLine() and TextFieldParser

On this page

A CSV file is a comma-separated file, that is used to store data in an organized way. It usually stores data in tabular form. Most of the business organizations store their data in CSV files.

In C#, we can perform various operations on a CSV file. We can read, write and alter a CSV file. This article focuses on two methods to read a CSV file and store its values into an array: reading lines with StreamReader, and parsing fields with TextFieldParser.

Both examples use the same sample Data.csv file:

Name,Age
Alice,30
Bob,25

Read a CSV file with StreamReader

The StreamReader class reads a file as a stream of text. File.OpenRead() opens the file, and ReadLine() returns one line at a time until EndOfStream is reached. Splitting each line on the comma gives the individual values, which the example stores in one list per column.

The correct syntax to use OpenRead() and ReadLine() method is as follows:

// OpenRead() Syntax
File.OpenRead(@"FilePath");
// ReadLine() Syntax
StreamReaderObject.ReadLine();

Example Code:

using System.IO;
using System.Collections.Generic;
using System;

class ReadingCSV {
  static void Main(string[] args) {
    var reader = new StreamReader(File.OpenRead(@"D:\New folder\Data.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]);
    }
    foreach (var column1 in listA) {
      Console.WriteLine(column1);
    }
    foreach (var column2 in listB) {
      Console.WriteLine(column2);
    }
  }
}

Output:

Name
Alice
Bob
Age
30
25

Splitting on the comma works when no field itself contains a comma. A quoted field such as "Smith, John" would be split in the wrong place; use TextFieldParser for files like that.

Parse CSV fields with TextFieldParser

The TextFieldParser class is defined in the Microsoft.VisualBasic.FileIO namespace. It parses a delimited file field by field and understands quoted fields. Set the delimiters with SetDelimiters(), then call ReadFields() to get the fields of the current line as a string array; the parser moves to the next line on every call. In a .NET Framework project, add a reference to Microsoft.VisualBasic before running the program below; in modern .NET the namespace is part of the shared framework.

The correct syntax to use this parser is as follows:

TextFieldParser ParserName = new TextFieldParser(PathString);

Example Code:

using System;
using System.Collections.Generic;
using Microsoft.VisualBasic.FileIO;

class ReadingCSV {
  public static void Main() {
    var path = @"D:\New folder\Data.csv";
    List<string> listA = new List<string>();
    List<string> listB = new List<string>();
    using (TextFieldParser csvReader = new TextFieldParser(path)) {
      csvReader.CommentTokens = new string[] { "#" };
      csvReader.SetDelimiters(new string[] { "," });
      csvReader.HasFieldsEnclosedInQuotes = true;

      // Skip the row with the column names
      csvReader.ReadLine();

      while (!csvReader.EndOfData) {
        // Read current line fields, pointer moves to the next line.
        string[] fields = csvReader.ReadFields();
        listA.Add(fields[0]);
        listB.Add(fields[1]);
      }
    }
    foreach (var column1 in listA) {
      Console.WriteLine(column1);
    }
    foreach (var column2 in listB) {
      Console.WriteLine(column2);
    }
  }
}

Output:

Alice
Bob
30
25

This time the header row is skipped with the initial ReadLine(), and the parser, not a manual split, decides where each field ends, so a quoted comma inside a field stays intact.