IC Improve Code Recipes

Recipe 11.1 · C#

A Correct CSV Writer

Problem

CSV looks trivial, so everyone writes their own. Then a field contains a comma, a quote or a line break, and the file shifts columns from that row onward. Numbers are written with the server's culture, so a German server writes 1234,5. Excel opens a UTF-8 file as Windows-1252 and turns Müller into Müller. And a field that begins with = becomes a formula when someone opens the file in Excel, which is a known injection vector.

The way it's often written

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

C#
var sb = new StringBuilder();
foreach (DataRow row in table.Rows)
{
    sb.AppendLine(row["Name"] + "," + row["City"] + "," +
        row["Balance"] + "," + row["Opened"]);
}
File.WriteAllText(path, sb.ToString());

No quoting, culture-dependent numbers and dates, the whole file built in memory, and UTF-8 without a byte order mark, which Excel misreads.

The improved recipe

The writer quotes fields only when needed, doubles embedded quotes, formats values with the invariant culture, neutralizes formula-like text, and streams rows to any TextWriter. Columns are defined once, with a header and a value selector, so the same definition can drive CSV and Excel output.

C#
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ImproveCode.Export;

public sealed record ExportColumn<T>(
    string Header, Func<T, object?> Value, string? Format = null);

public sealed class CsvWriter
{
    private static readonly char[] FormulaStarts =
        ['=', '+', '-', '@', '\t', '\r'];

    private readonly TextWriter _writer;
    private readonly char _delimiter;
    private readonly bool _protectFormulas;

    public CsvWriter(
        TextWriter writer, char delimiter = ',',
        bool protectFormulas = true)
    {
        ArgumentNullException.ThrowIfNull(writer);
        _writer = writer;
        _delimiter = delimiter;
        _protectFormulas = protectFormulas;
    }

    public static StreamWriter CreateFile(
        string path, bool forExcel = true) =>
        new(path, append: false,
            new UTF8Encoding(encoderShouldEmitUTF8Identifier: forExcel));

    public Task WriteRowAsync(
        IEnumerable<string?> fields, CancellationToken ct = default)
    {
        string line = string.Join(_delimiter,
            fields.Select(f => Escape(f, _delimiter, _protectFormulas)));
        return _writer.WriteAsync((line + "\r\n").AsMemory(), ct);
    }

    public async Task WriteRecordsAsync<T>(
        IEnumerable<T> records,
        IReadOnlyList<ExportColumn<T>> columns,
        CancellationToken ct = default)
    {
        ArgumentNullException.ThrowIfNull(records);
        ArgumentNullException.ThrowIfNull(columns);

        await WriteRowAsync(columns.Select(c => c.Header), ct);
        foreach (T record in records)
        {
            await WriteRowAsync(
                columns.Select(c => FormatValue(c.Value(record), c.Format)),
                ct);
        }
        await _writer.FlushAsync(ct);
    }

    public static string FormatValue(object? value, string? format)
    {
        var inv = CultureInfo.InvariantCulture;
        return value switch
        {
            null => "",
            DateTime d => d.ToString(format ?? "yyyy-MM-dd HH:mm:ss", inv),
            DateOnly d => d.ToString(format ?? "yyyy-MM-dd", inv),
            bool b => b ? "true" : "false",
            IFormattable f => f.ToString(format, inv),
            _ => value.ToString() ?? ""
        };
    }

    public static string Escape(
        string? field, char delimiter = ',', bool protectFormulas = true)
    {
        if (string.IsNullOrEmpty(field))
        {
            return "";
        }

        if (protectFormulas
            && field.IndexOfAny(FormulaStarts) == 0
            && !double.TryParse(field, NumberStyles.Float,
                CultureInfo.InvariantCulture, out _))
        {
            field = "'" + field;
        }

        bool mustQuote = field.Contains(delimiter)
            || field.Contains('"') || field.Contains('\n')
            || field.Contains('\r')
            || field[0] == ' ' || field[^1] == ' ';

        return mustQuote
            ? "\"" + field.Replace("\"", "\"\"") + "\""
            : field;
    }
}

A usage snippet:

C#
var columns = new ExportColumn<Customer>[]
{
    new("Customer", c => c.Name),
    new("City", c => c.City),
    new("Balance", c => c.Balance, "0.00"),
    new("Opened", c => c.OpenedOn)
};

await using var file = CsvWriter.CreateFile(@"D:\exports\customers.csv");
await new CsvWriter(file).WriteRecordsAsync(customers, columns, ct);

How it works

The rules come from RFC 4180, the closest thing CSV has to a standard. A field is quoted when it contains the delimiter, a quote, or a line break, and embedded quotes are doubled: Say "hi" becomes "Say ""hi""". Fields with leading or trailing spaces are quoted too, because some readers trim unquoted whitespace. Rows end with CRLF, as the RFC specifies; every reader I know accepts it.

FormatValue uses the invariant culture for every number and date, so the file is the same on every server. Dates default to ISO 8601 (2025-06-30), which sorts correctly as text and which Excel and SQL Server both parse. Pass a format per column when a consumer needs something else.

Formula protection follows the OWASP advice for CSV injection: a text field that starts with =, +, -, @, a tab or a carriage return gets a leading apostrophe, so Excel shows it as text instead of evaluating it. Real numbers such as -42.5 are left alone. Turn protection off for files that go only to other programs, since the apostrophe becomes part of the data there.

CreateFile controls the byte order mark. With forExcel: true the file starts with the UTF-8 BOM, which is how Excel knows the file is UTF-8 when a user double-clicks it. Many Unix tools and some import programs treat the BOM as part of the first header, so pass false for machine-to-machine files.

Variations and pitfalls

  • Semicolons for European Excel. Excel uses the list separator from the user's regional settings. For users in much of Europe that is ;. Pass ';' as the delimiter, or give them an .xlsx (Recipe 11.3) and avoid the question.
  • Streaming to a web response. Wrap Response.Body in a StreamWriter and write records as they come from the database. Memory stays flat for any size.
  • Atomic output. For files other systems pick up, write through AtomicFile.WriteAsync from Recipe 10.2.
  • CsvHelper. The CsvHelper package is excellent and handles class mapping, type conversion and many dialects. I use this small writer when a project only needs to produce a few known files.