IC Improve Code Recipes

Recipe 11.2 · C#

A Correct CSV Reader

Problem

The usual reader calls line.Split(','). That breaks on the first quoted field containing a comma, and ReadLine breaks on the first quoted field containing a line break. Import files from banks and partners have both. The resulting bugs are silent: values land in the wrong columns and get imported anyway.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
foreach (string line in File.ReadAllLines(path).Skip(1))
{
    string[] parts = line.Split(',');
    var c = new Customer
    {
        Name = parts[0].Trim('"'),
        Balance = decimal.Parse(parts[2])
    };
    Save(c);
}

"Smith, John" becomes two fields, decimal.Parse uses the server's culture, and the whole file is in memory.

The improved recipe

A small state machine reads characters, tracks whether it is inside quotes, and yields one record at a time. A header-aware wrapper gives access by column name, so a partner adding a column does not break the import.

C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ImproveCode.Export;

public static class CsvReader
{
    public static IEnumerable<string[]> ReadRecords(
        TextReader reader,
        char delimiter = ',',
        int maxFieldLength = 1 << 20)
    {
        ArgumentNullException.ThrowIfNull(reader);
        var fields = new List<string>();
        var field = new StringBuilder();
        bool inQuotes = false;
        bool rowHasData = false;
        long line = 1;
        int c;

        while ((c = reader.Read()) != -1)
        {
            char ch = (char)c;
            if (inQuotes)
            {
                if (ch == '"')
                {
                    if (reader.Peek() == '"')
                    {
                        field.Append('"');
                        reader.Read();
                    }
                    else
                    {
                        inQuotes = false;
                    }
                }
                else
                {
                    if (ch == '\n') line++;
                    field.Append(ch);
                }
            }
            else if (ch == '"' && field.Length == 0)
            {
                inQuotes = true;
                rowHasData = true;
            }
            else if (ch == delimiter)
            {
                fields.Add(field.ToString());
                field.Clear();
                rowHasData = true;
            }
            else if (ch == '\r' || ch == '\n')
            {
                if (ch == '\r' && reader.Peek() == '\n') reader.Read();
                line++;
                if (rowHasData || field.Length > 0)
                {
                    fields.Add(field.ToString());
                    yield return fields.ToArray();
                }
                fields.Clear();
                field.Clear();
                rowHasData = false;
            }
            else
            {
                field.Append(ch);
                rowHasData = true;
            }

            if (field.Length > maxFieldLength)
            {
                throw new InvalidDataException(
                    $"Field too long near line {line}.");
            }
        }

        if (inQuotes)
        {
            throw new InvalidDataException(
                $"Unterminated quoted field near line {line}.");
        }
        if (rowHasData || field.Length > 0)
        {
            fields.Add(field.ToString());
            yield return fields.ToArray();
        }
    }

    public static IEnumerable<CsvRow> ReadWithHeader(
        TextReader reader, char delimiter = ',')
    {
        using var records = ReadRecords(reader, delimiter).GetEnumerator();
        if (!records.MoveNext())
        {
            yield break;
        }

        var index = records.Current
            .Select((name, i) => (Name: name.Trim(), i))
            .GroupBy(x => x.Name, StringComparer.OrdinalIgnoreCase)
            .ToDictionary(g => g.Key, g => g.First().i,
                StringComparer.OrdinalIgnoreCase);

        int rowNumber = 1;
        while (records.MoveNext())
        {
            rowNumber++;
            yield return new CsvRow(rowNumber, records.Current, index);
        }
    }
}

public sealed class CsvRow
{
    private readonly string[] _fields;
    private readonly IReadOnlyDictionary<string, int> _index;

    public CsvRow(int rowNumber, string[] fields,
        IReadOnlyDictionary<string, int> index)
    {
        RowNumber = rowNumber;
        _fields = fields;
        _index = index;
    }

    public int RowNumber { get; }

    public bool HasColumn(string name) => _index.ContainsKey(name);

    public string? this[string column] =>
        _index.TryGetValue(column, out int i) && i < _fields.Length
            ? _fields[i]
            : null;
}

A usage snippet that parses with the invariant culture and collects errors per row:

C#
using var reader = new StreamReader(
    path, detectEncodingFromByteOrderMarks: true);
foreach (var row in CsvReader.ReadWithHeader(reader))
{
    if (!decimal.TryParse(row["Balance"], NumberStyles.Number,
            CultureInfo.InvariantCulture, out decimal balance))
    {
        errors.Add($"Row {row.RowNumber}: Balance is not a number.");
        continue;
    }
    // ...
}

How it works

The reader keeps one piece of state that matters: whether it is inside a quoted field. Inside quotes, delimiters and line breaks are data, and a doubled quote is one literal quote. Outside quotes, a delimiter ends a field and a line break ends a record. CRLF, LF and lone CR line endings all work, so files from Windows, Unix and old Mac exports read the same. Blank lines are skipped.

Records are yielded one at a time from a TextReader, so a 2 GB file is read with a few kilobytes of memory. StreamReader buffers internally, which keeps the per-character Read calls cheap. With detectEncodingFromByteOrderMarks: true it also removes the BOM that the writer in Recipe 11.1 adds for Excel, so the first header is Customer, not \uFEFFCustomer.

Two checks protect the import from broken or hostile input. An unterminated quote throws with an approximate line number instead of silently swallowing the rest of the file into one field. And a field longer than one million characters throws, so a missing quote cannot build a gigabyte string.

ReadWithHeader maps header names to positions, ignoring case and surrounding spaces. Code asks for row["Balance"], and the import keeps working when a partner reorders columns or adds new ones. A missing column returns null, which your validation reports. RowNumber counts records, with the header as row 1; that matches what users see in Excel unless fields contain line breaks.

The round trip is the test that matters: anything the writer produces, the reader returns unchanged. I keep that as a unit test with commas, quotes, line breaks, leading spaces and non-Latin text in the fields.

Variations and pitfalls

  • Parse with the invariant culture. The reader returns strings. Use CultureInfo.InvariantCulture for numbers and DateOnly.TryParseExact with the formats the partner specified.
  • Unknown encodings. Old files from Windows systems may be Windows-1252, not UTF-8. On modern .NET, call Encoding.RegisterProvider(CodePagesEncodingProvider.Instance) once before Encoding.GetEncoding(1252) will work. Agree on UTF-8 for new feeds.
  • Bulk loading. For large imports, feed parsed rows into SqlBulkCopy (Chapter 1) instead of inserting row by row.
  • Validate rows, not files. Collect errors per row with the row number, and decide up front whether one bad row rejects the file or is written to a rejects file.