How To Read A CSV File In C#

code snippet Mar 15, 2019

Scenario

You want to read a CSV file and store it in a list in memory for processing. The CSV file has headers: Id (int), Name (string), Description (string).

The file is stored in the App_Data folder of your application.

(Remember to set its Copy to Output Directory property to Copy always).

Code


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace CodeSnippet
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var path = "App_Data/Data.csv";	// path to the CSV file
            var rows = await File.ReadAllLinesAsync(path);

            // SOLUTION 1: We only care about the id column
            var allIds = new List();
            allIds.AddRange(rows
                .Skip(1) // skip the header row
                .Select(x => Convert.ToInt32(x.Split(',')[0])
                ));

            // SOLUTION 2: We want to store the rows as objects
            var allEntries = new List();

            // Skip the header row
            foreach (var row in rows.Skip(1))
            {
                var column = row.Split(',');
                allEntries.Add(new Entry
                {
                    Id = Convert.ToInt32(column[0]),
                    Name = column[1],
                    Description = column[2]
                });
            }
        }
    }

    public class Entry
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }
}

unsplash-logoThought Catalog

Kristina Alberto

Software engineer from Sydney. I work at Domain Group.