CSV
suggest changeCSV (comma-separated values) is the most common format for exchanging tabular data: spreadsheet exports, bank statements, database dumps, reports. It looks trivial, but the format has rules that a naive string.Split(',') breaks:
- A field that contains the delimiter, a double quote or a line break must be enclosed in double quotes.
- A double quote inside a quoted field is written twice:
"He said ""hi""". - A quoted field can span several physical lines.
- Line endings are
\r\nper RFC 4180, but\nis common too. - There is no standard for types, encoding or even the delimiter. Excel in many European locales writes
;and uses,as the decimal separator.
.NET has no CSV class in System.*. Your options are:
- write a small parser and writer yourself (fine for simple, trusted data)
Microsoft.VisualBasic.FileIO.TextFieldParser, which ships with .NET and works from C#- the CsvHelper NuGet package, the de facto standard for real-world CSV
Examples use C# 14 / .NET 10 and run as file-based programs (dotnet run app.cs).
Why string.Split is not enough
string line = "42,\"Smith, John\",\"He said \"\"hi\"\"\",9.99";
string[] parts = line.Split(',');
Console.WriteLine(parts.Length);
foreach (var p in parts) Console.WriteLine($"[{p}]");
5
[42]
["Smith]
[ John"]
["He said ""hi"""]
[9.99]
The line has 4 fields, but Split returns 5, keeps the quotes and doesn't unescape "". Reading a file with File.ReadLines and splitting each line is also wrong, because a quoted field can contain a newline. Split is only safe when you control the data and know that no field contains a comma, quote or line break.
Writing CSV
Writing is the easy direction. Quote a field only when it needs it and double any quotes inside:
using System.Globalization;
using System.Text;
static string Escape(string? field)
{
if (string.IsNullOrEmpty(field)) return "";
bool needsQuotes = field.AsSpan().IndexOfAny(",\"\r\n") >= 0
|| field[0] == ' ' || field[^1] == ' ';
if (!needsQuotes) return field;
return "\"" + field.Replace("\"", "\"\"") + "\"";
}
static string ToCsvLine(IEnumerable<string?> fields) =>
string.Join(",", fields.Select(Escape));
var rows = new List<string?[]>
{
new[] { "id", "name", "note", "price" },
new[] { "1", "Widget", "plain", 9.99m.ToString(CultureInfo.InvariantCulture) },
new[] { "2", "Smith, John", "He said \"hi\"", "12.5" },
new[] { "3", "Multi", "line one\nline two", null },
};
var sb = new StringBuilder();
foreach (var row in rows) sb.Append(ToCsvLine(row)).Append("\r\n");
Console.Write(sb.ToString());
id,name,note,price
1,Widget,plain,9.99
2,"Smith, John","He said ""hi""",12.5
3,Multi,"line one
line two",
Leading and trailing spaces are quoted too, because some readers trim unquoted fields. null becomes an empty field. CSV can't tell null and "" apart, so if the difference matters you have to pick a convention (for example \N, as MySQL does).
Numbers are converted with CultureInfo.InvariantCulture. That's not optional, as the next section shows.
Culture: the most common CSV bug
decimal.ToString(), string interpolation and decimal.Parse all use the current culture. On a machine set to German, Polish or French the decimal separator is a comma, which silently corrupts CSV output and input:
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE");
decimal price = 1234.5m;
Console.WriteLine($"Widget,{price}");
Console.WriteLine($"Widget,{price.ToString(CultureInfo.InvariantCulture)}");
Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $"Widget,{price}"));
Console.WriteLine(decimal.Parse("1234.5"));
Console.WriteLine(decimal.Parse("1234.5", CultureInfo.InvariantCulture));
Console.WriteLine(CultureInfo.CurrentCulture.TextInfo.ListSeparator);
Widget,1234,5
Widget,1234.5
Widget,1234.5
12345
1234,5
;
The first line now has 3 fields instead of 2, and parsing "1234.5" under de-DE returns 12345 because . is the thousands separator there. Always pass CultureInfo.InvariantCulture when formatting or parsing values for a file. string.Create(IFormatProvider, ...) formats a whole interpolated string with a given culture.
TextInfo.ListSeparator is the separator Excel uses for that locale. If you produce files for people who double-click them in a German Excel, write ; and format numbers with that culture. For files read by programs, use , and the invariant culture.
Writing a file for Excel
Excel assumes the system ANSI code page for CSV files unless the file starts with a UTF-8 byte order mark. Also, a field that starts with =, +, - or @ is evaluated as a formula, which is a known attack vector (CSV injection) when exporting user-supplied text:
using System.Globalization;
using System.Text;
static string Escape(string field)
{
if (field.Length > 0 && "=+-@\t\r".Contains(field[0]))
field = "'" + field; // neutralize spreadsheet formulas
if (field.AsSpan().IndexOfAny(",\"\r\n") < 0) return field;
return "\"" + field.Replace("\"", "\"\"") + "\"";
}
var people = new[]
{
(Name: "Zoë", Age: 31, Balance: 1234.5m),
(Name: "=HYPERLINK(\"http://evil\")", Age: 0, Balance: -5m),
};
string path = Path.Combine(Path.GetTempPath(), "people.csv");
using (var w = new StreamWriter(path, false, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true)))
{
w.NewLine = "\r\n";
w.WriteLine("name,age,balance");
foreach (var p in people)
{
w.WriteLine(string.Join(",",
Escape(p.Name),
p.Age.ToString(CultureInfo.InvariantCulture),
p.Balance.ToString(CultureInfo.InvariantCulture)));
}
}
byte[] bytes = File.ReadAllBytes(path);
Console.WriteLine(Convert.ToHexString(bytes, 0, 3));
Console.Write(File.ReadAllText(path));
File.Delete(path);
EFBBBF
name,age,balance
Zoë,31,1234.5
"'=HYPERLINK(""http://evil"")",0,-5
EFBBBF is the UTF-8 BOM. new StreamWriter(path) without an encoding writes UTF-8 without a BOM, which is what most other tools prefer, so only add it when the consumer is Excel. Writing line by line to a StreamWriter keeps memory use flat no matter how many rows you export. Formula escaping is applied only to text columns: real numbers like -5 must stay as they are. See Writing lines to a file using the System.IO.StreamWriter class for more on StreamWriter.
A small, correct parser
If you can't take a dependency, a character-by-character state machine handles quoting, escaped quotes and multi-line fields. It reads from any TextReader, so it works on strings, files and network streams, and it yields rows lazily:
using System.Text;
static IEnumerable<string[]> ReadCsv(TextReader reader, char delimiter = ',')
{
var fields = new List<string>();
var field = new StringBuilder();
bool inQuotes = false;
bool rowHasData = false;
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 field.Append(ch);
continue;
}
if (ch == '"') { 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();
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 (inQuotes) throw new FormatException("Unterminated quoted field");
if (rowHasData || field.Length > 0)
{
fields.Add(field.ToString());
yield return fields.ToArray();
}
}
string csv = """"
id,name,note,price
1,Widget,plain,9.99
2,"Smith, John","He said ""hi""",12.5
3,Multi,"line one
line two",
4,,"",0
"""";
foreach (string[] row in ReadCsv(new StringReader(csv)))
Console.WriteLine($"{row.Length}: " + string.Join(" | ", row.Select(f => $"[{f}]")));
4: [id] | [name] | [note] | [price]
4: [1] | [Widget] | [plain] | [9.99]
4: [2] | [Smith, John] | [He said "hi"] | [12.5]
4: [3] | [Multi] | [line one
line two] | []
4: [4] | [] | [] | [0]
Notes on the design:
\r\n,\nand\rare all accepted as row terminators, while line breaks inside quotes are kept as part of the field.- Empty lines are skipped, and a missing newline at the end of the file is handled.
- The raw string literal uses four quotes (
"""") because the content itself contains""".
What it doesn't do: detect the delimiter, handle a BOM (use StreamReader, which strips it), report line numbers, or convert types. Once you need those, use a library.
Mapping rows to objects
Read the header row first and look columns up by name, so the code keeps working when someone reorders columns. Using ReadCsv from above:
using System.Globalization;
string path = Path.Combine(Path.GetTempPath(), "sales.csv");
File.WriteAllText(path, "region,amount,date\r\nNorth,120.50,2026-01-15\r\nSouth,80,2026-01-16\r\nNorth,99.5,2026-02-01\r\n");
using var reader = File.OpenText(path);
using var rows = ReadCsv(reader).GetEnumerator();
if (!rows.MoveNext()) return;
var col = rows.Current
.Select((name, i) => (name, i))
.ToDictionary(x => x.name, x => x.i, StringComparer.OrdinalIgnoreCase);
var sales = new List<Sale>();
while (rows.MoveNext())
{
string[] r = rows.Current;
sales.Add(new Sale(
r[col["region"]],
decimal.Parse(r[col["amount"]], CultureInfo.InvariantCulture),
DateOnly.ParseExact(r[col["date"]], "yyyy-MM-dd", CultureInfo.InvariantCulture)));
}
foreach (var g in sales.GroupBy(s => s.Region))
Console.WriteLine($"{g.Key}: {g.Sum(s => s.Amount)}");
reader.Close();
File.Delete(path);
record Sale(string Region, decimal Amount, DateOnly Date);
North: 220.00
South: 80
File.OpenText returns a StreamReader that detects UTF-8 with or without a BOM. Because ReadCsv is lazy, only one row is in memory at a time, so this works on multi-gigabyte files as well.
TextFieldParser
TextFieldParser lives in the Microsoft.VisualBasic.FileIO namespace, but it's an ordinary .NET class that's part of the shared framework, so no package reference is needed:
using Microsoft.VisualBasic.FileIO;
string csv = """"
id,name,note
1,"Smith, John","He said ""hi"""
2,Multi,"line one
line two"
"""";
using var parser = new TextFieldParser(new StringReader(csv));
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
parser.HasFieldsEnclosedInQuotes = true;
while (!parser.EndOfData)
{
long lineNo = parser.LineNumber;
string[]? fields = parser.ReadFields();
Console.WriteLine($"line {lineNo}: {string.Join(" | ", fields!)}");
}
line 1: id | name | note
line 2: 1 | Smith, John | He said "hi"
line 3: 2 | Multi | line one
line two
It handles quotes and multi-line fields correctly and throws MalformedLineException on broken input. It returns only strings, it's slow compared to CsvHelper, and it trims whitespace around fields by default (TrimWhiteSpace = true). It's a reasonable choice for a quick script with no dependencies.
CsvHelper
For production code, use CsvHelper (dotnet add package CsvHelper). It's fast, streams data, maps columns to properties by header name and converts types using a culture you specify.
Reading and writing records
#:package CsvHelper@33.1.0
using System.Globalization;
using CsvHelper;
string path = Path.Combine(Path.GetTempPath(), "products.csv");
File.WriteAllText(path, """"
Id,Name,Price,InStock
1,Widget,9.99,true
2,"Gadget, large",24.50,false
3,"The ""Best"" Thing",100,true
"""");
using (var reader = new StreamReader(path))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
foreach (Product p in csv.GetRecords<Product>())
Console.WriteLine(p);
}
var products = new List<Product>
{
new(10, "Café au lait", 3.5m, true),
new(11, "Comma, inc.", 1234.5m, false),
};
using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.WriteRecords(products);
Console.Write(writer.ToString());
}
File.Delete(path);
public record Product(int Id, string Name, decimal Price, bool InStock);
Product { Id = 1, Name = Widget, Price = 9.99, InStock = True }
Product { Id = 2, Name = Gadget, large, Price = 24.50, InStock = False }
Product { Id = 3, Name = The "Best" Thing, Price = 100, InStock = True }
Id,Name,Price,InStock
10,Café au lait,3.5,True
11,"Comma, inc.",1234.5,False
Things to know:
GetRecords<T>()is lazy: it yields records as it reads. Consume it while the reader is open. Calling.ToList()after theusingblock ends throws.- Records with a primary constructor work. CsvHelper matches header names to constructor parameters or properties.
WriteRecordswrites a header row from the property names, then one row per object, quoting only when needed.- The culture is a required constructor argument on purpose. Pass
CultureInfo.InvariantCultureunless you are reading locale-specific files.
Custom headers, delimiters and formats
Real files have column names with spaces, semicolon delimiters and local number and date formats. A CsvConfiguration sets the format, and a ClassMap maps columns to properties without putting attributes on your model:
#:package CsvHelper@33.1.0
using System.Globalization;
using CsvHelper;
using CsvHelper.Configuration;
string data = """
Order No;Customer;Total;Date
A-1;Kowalski;1.234,50;17.10.2026
A-2;Müller;99,90;01.02.2026
""";
var de = CultureInfo.GetCultureInfo("de-DE");
var config = new CsvConfiguration(de)
{
Delimiter = ";",
TrimOptions = TrimOptions.Trim,
};
using var csv = new CsvReader(new StringReader(data), config);
csv.Context.RegisterClassMap<OrderMap>();
foreach (var o in csv.GetRecords<Order>())
Console.WriteLine($"{o.Number} {o.Customer} {o.Total.ToString(CultureInfo.InvariantCulture)} {o.Date:yyyy-MM-dd}");
public class Order
{
public string Number { get; set; } = "";
public string Customer { get; set; } = "";
public decimal Total { get; set; }
public DateOnly Date { get; set; }
}
public sealed class OrderMap : ClassMap<Order>
{
public OrderMap()
{
Map(o => o.Number).Name("Order No");
Map(o => o.Customer);
Map(o => o.Total);
Map(o => o.Date).TypeConverterOption.Format("dd.MM.yyyy");
}
}
A-1 Kowalski 1234.50 2026-10-17
A-2 Müller 99.90 2026-02-01
The German culture makes 1.234,50 parse as 1234.50. Other useful CsvConfiguration options are HasHeaderRecord = false (then map columns with .Index(n)), PrepareHeaderForMatch (for example args => args.Header.ToLowerInvariant() for case-insensitive headers), and DetectDelimiter = true.
Attributes and handling bad rows
If you prefer, put the mapping on the class with attributes. To handle bad data row by row instead of failing the whole import, read manually with Read and GetRecord<T>:
#:package CsvHelper@33.1.0
using System.Globalization;
using CsvHelper;
using CsvHelper.Configuration.Attributes;
string data = """
sku,qty,comment
X1,5,ok
X2,five,typo
X3,7
""";
using var csv = new CsvReader(new StringReader(data), CultureInfo.InvariantCulture);
csv.Read();
csv.ReadHeader();
while (csv.Read())
{
try
{
var line = csv.GetRecord<Line>();
Console.WriteLine($"row {csv.Parser.Row}: {line.Sku} x {line.Quantity} ({line.Comment ?? "null"})");
}
catch (CsvHelperException ex)
{
Console.WriteLine($"row {csv.Parser.Row}: {ex.GetType().Name}, raw: {csv.Parser.RawRecord.TrimEnd()}");
}
}
public class Line
{
[Name("sku")] public string Sku { get; set; } = "";
[Name("qty")] public int Quantity { get; set; }
[Name("comment"), Optional] public string? Comment { get; set; }
}
row 2: X1 x 5 (ok)
row 3: TypeConverterException, raw: X2,five,typo
row 4: MissingFieldException, raw: X3,7
Parser.Row is the 1-based row number and Parser.RawRecord is the original text, both useful in error reports. [Optional] means the column may be absent from the header. It doesn't cover a row that's shorter than the header, which still throws MissingFieldException. To accept short rows, set MissingFieldFound = null in the configuration:
var config = new CsvConfiguration(CultureInfo.InvariantCulture) { MissingFieldFound = null };
using var csv = new CsvReader(new StringReader(data), config);
row 2: X1 x 5 (ok)
row 3: TypeConverterException, raw: X2,five,typo
row 4: X3 x 7 ()
The missing field becomes an empty string, not null. There's also BadDataFound (called for a stray quote inside an unquoted field) and ReadingExceptionOccurred for central error handling.
Summary
- Don't parse CSV with
string.Splitor line by line unless you control the data. Quoted fields can contain commas, quotes and newlines. - When writing, quote fields containing the delimiter,
",\ror\n, and double the inner quotes. - Always format and parse numbers and dates with
CultureInfo.InvariantCulture(or an explicit culture for locale-specific files). - Add a UTF-8 BOM and guard against formula injection only when the file is meant to be opened in Excel.
- Stream large files: write rows with a
StreamWriterand read them lazily rather than loading everything withFile.ReadAllText. - For anything beyond trivial data, use CsvHelper:
GetRecords<T>/WriteRecords, aCsvConfigurationfor the format and aClassMapor attributes for mapping.