Skip to main content

Command Palette

Search for a command to run...

C# CSV Reader

Updated
3 min read
C

Researching and writing articles about document processing.

When working with data in .NET applications, you might often find yourself needing to read from or write to CSV (Comma Separated Values) files. In C#, there are multiple ways to read CSV files, ranging from using the built-in library to leveraging third-party packages for more complex needs. In this guide, we'll cover a practical approach to reading CSV files in C# with examples.

Using the TextFieldParser Class

One of the simplest ways to read CSV files in C# without installing additional packages is by using the TextFieldParser class from the Microsoft.VisualBasic.FileIO namespace. Despite being in the VisualBasic namespace, it's fully usable in C# and provides a straightforward way to parse CSV files.

using System;
using Microsoft.VisualBasic.FileIO;

namespace CSVReaderExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string csvFilePath = @"path\to\your\csvfile.csv";

            using (TextFieldParser csvParser = new TextFieldParser(csvFilePath))
            {
                csvParser.CommentTokens = new string[] { "#" };
                csvParser.SetDelimiters(new string[] { "," });
                csvParser.HasFieldsEnclosedInQuotes = true;

                // Skip the header
                csvParser.ReadLine();

                while (!csvParser.EndOfData)
                {
                    string[] fields = csvParser.ReadFields();
                    Console.WriteLine("Processing Row:");
                    foreach (string field in fields)
                    {
                        //TODO: Process field
                        Console.WriteLine(field);
                    }
                }
            }
        }
    }
}

Using a Third-Party Library: CsvHelper

For more complex CSV processing, including class mapping and asynchronous reading, you might want to use a third-party library like CsvHelper. CsvHelper is a highly popular and efficient library for dealing with CSV files in .NET applications.

First, install the CsvHelper package via NuGet:

Install-Package CsvHelper
using System;
using System.Globalization;
using System.IO;
using CsvHelper;
using CsvHelper.Configuration;
using System.Collections.Generic;

namespace CsvHelperExample
{
    public class YourDataClass
    {
        public string Column1 { get; set; }
        public int Column2 { get; set; }
        // Add other properties corresponding to CSV columns
    }

    class Program
    {
        static void Main(string[] args)
        {
            string csvFilePath = @"path\to\your\csvfile.csv";
            var config = new CsvConfiguration(CultureInfo.InvariantCulture)
            {
                NewLine = Environment.NewLine,
            };

            using (var reader = new StreamReader(csvFilePath))
            using (var csv = new CsvReader(reader, config))
            {
                var records = csv.GetRecords<YourDataClass>();
                foreach (var record in records)
                {
                    Console.WriteLine($"Column1: {record.Column1}, Column2: {record.Column2}");
                }
            }
        }
    }
}

Tips for Efficient CSV Processing

  • Handle Large Files: If you're dealing with large CSV files, consider reading and processing the file line by line rather than loading the entire file into memory.

  • Data Validation: Always validate the data you read from a CSV file, especially if the data source is not controlled by you.

  • Error Handling: Implement comprehensive error handling, especially for type conversion errors when casting string values from the CSV to other data types.

Reading CSV files in C# is a common requirement for many applications dealing with data. By using the built-in TextFieldParser class or leveraging powerful third-party libraries like CsvHelper, you can easily integrate CSV processing into your .NET applications.

More from this blog

C

CSV processing

11 posts

Articles about CSV processing