Your app receives a CSV file from a partner or an export, and you need the rows as C# objects: numbers as numbers, dates as dates, and no crash on the one broken line in row 40,000. A string.Split(',') loop breaks the first time a name contains a comma in quotes.
CsvHelper (official docs) is the usual answer to read a CSV file in C#. It handles quotes, headers, culture and type conversion for you. The code below was built and run on .NET 10 with CsvHelper 33.1.0, and the section on the new API was run with CsvHelper 34.1.0. Nothing here needs a web server.
This is the flow the article builds: read rows, map them to a class, and report bad rows instead of failing the whole file.

- Which approach should you choose?
- Prerequisites
- Step 1: Create a sample CSV file
- Step 2: Read a CSV file into a class
- Step 3: ClassMap, headers and culture
- Step 4: Missing fields and bad data
- Dynamic, records and reading field by field
- Read a large CSV file asynchronously
- Write a CSV file
- CsvHelper 34: the new API
- What the output looks like
- Common problems and fixes
- Frequently asked questions
- Summary
Which approach should you choose?
- CsvHelper 33.1.0: the long-standing API (
CsvConfiguration,ClassMap, culture argument). Almost every existing tutorial, Stack Overflow answer and code base uses it, so pick it when you maintain existing code or want the most examples. - CsvHelper 34.x: a rewrite released in 2026 with a different API (source-generated
[CsvRecord]types,CsvReaderOptions, noClassMap). Pick it for new code on .NET 8 or later. See the section below and the migration guide. - Need a comparison with
StreamReaderorTextFieldParserand no package? See Read a CSV file in .NET Core and Read a CSV file using TextFieldParser. This article only covers CsvHelper.
The main sections use the 33.1.0 API. Pin the version in your project file so an upgrade does not break the build:
Prerequisites
- A .NET 8, 9 or 10 project (a console app is enough).
- The CsvHelper package, pinned to the API you follow.
dotnet add package CsvHelper --version 33.1.0
Step 1: Create a sample CSV file
One name contains a comma (quoted), and one salary is empty. Those are the cases that break hand-written parsers.
File.WriteAllText("employees.csv",
"Id,Name,Salary,JoinDate\n1,Asha,5200.50,2022-03-14\n2,Ravi,,2021-11-01\n3,\"Smith, John\",4800,2020-07-30\n");
Step 2: Read a CSV file into a class
CsvReader needs a TextReader and a culture. GetRecords<T>() matches header names to property names and converts each value. Use a nullable type such as decimal? for columns that can be empty.
using System.Globalization;
using CsvHelper;
using CsvHelper.Configuration;
using CsvHelper.TypeConversion;
using (var reader = new StreamReader("employees.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
foreach (var e in csv.GetRecords<Employee>())
Console.WriteLine($"{e.Id} | {e.Name} | {e.Salary?.ToString() ?? "null"} | {e.JoinDate:yyyy-MM-dd}");
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; } = "";
public decimal? Salary { get; set; }
public DateTime JoinDate { get; set; }
}
GetRecords is lazy: it reads one row each time the loop moves, so call .ToList() only when you need everything in memory.
Step 3: ClassMap, headers and culture
Culture decides how numbers and dates are parsed. Use CultureInfo.InvariantCulture for machine-generated files. If the file was exported in a European locale (5200,50 with ; as the separator), pass that culture and delimiter instead, or the value is read wrongly or throws.
ClassMap is for when the header names do not match your property names, when you want defaults, or when you do not want attributes on the class. Register it on the reader context:
File.WriteAllText("people.csv", "emp_id;full_name;pay\n1;Asha;5200,50\n2;Ravi;4800,00\n");
var deConfig = new CsvConfiguration(new CultureInfo("de-DE")) { Delimiter = ";" };
using (var reader = new StreamReader("people.csv"))
using (var csv = new CsvReader(reader, deConfig))
{
csv.Context.RegisterClassMap<EmployeeMap>();
foreach (var e in csv.GetRecords<Employee>())
Console.WriteLine($"{e.Id} | {e.Name} | {e.Salary}");
}
public sealed class EmployeeMap : ClassMap<Employee>
{
public EmployeeMap()
{
Map(m => m.Id).Name("emp_id");
Map(m => m.Name).Name("full_name");
Map(m => m.Salary).Name("pay");
Map(m => m.JoinDate).Optional().Default(new DateTime(2000, 1, 1));
}
}
Optional() lets a column be absent from the header, and Default() supplies the value then.
No header row? Set HasHeaderRecord = false and map by position with Index:
File.WriteAllText("noheader.csv", "1,Asha,5200.50\n2,Ravi,4800\n");
var noHeader = new CsvConfiguration(CultureInfo.InvariantCulture) { HasHeaderRecord = false };
using (var reader = new StreamReader("noheader.csv"))
using (var csv = new CsvReader(reader, noHeader))
{
csv.Context.RegisterClassMap<IndexMap>();
foreach (var e in csv.GetRecords<Employee>())
Console.WriteLine($"{e.Id} | {e.Name} | {e.Salary}");
}
public sealed class IndexMap : ClassMap<Employee>
{
public IndexMap()
{
Map(m => m.Id).Index(0);
Map(m => m.Name).Index(1);
Map(m => m.Salary).Index(2);
Map(m => m.JoinDate).Ignore();
}
}
Step 4: Missing fields and bad data
By default CsvHelper is strict. A header that does not match a property throws HeaderValidationException, a short row throws MissingFieldException, and a value that cannot be converted throws TypeConverterException. That is right for a file you control. For files from outside, decide per case what should happen. This file has a letter in an Id and a row with only two fields:
File.WriteAllText("bad.csv", "Id,Name,Salary,JoinDate\n1,Asha,5200,2022-03-14\nx,Ravi,4800,2021-11-01\n3,Neha\n4,Omar,3900,2020-01-05\n");
var errors = new List<string>();
var badConfig = new CsvConfiguration(CultureInfo.InvariantCulture)
{
MissingFieldFound = null, // short rows do not throw here
HeaderValidated = null, // header mismatch does not throw
BadDataFound = args => errors.Add($"bad data row {args.Context.Parser.Row}: {args.RawRecord.Trim()}"),
ReadingExceptionOccurred = args =>
{
var row = args.Exception.Context?.Parser?.Row;
errors.Add(args.Exception is TypeConverterException tc
? $"row {row}: cannot convert '{tc.Text}' for {tc.MemberMapData.Member?.Name}"
: $"row {row}: {args.Exception.Message.Split('\n')[0]}");
return false; // skip the row, keep reading
}
};
using (var reader = new StreamReader("bad.csv"))
using (var csv = new CsvReader(reader, badConfig))
{
foreach (var e in csv.GetRecords<Employee>())
Console.WriteLine($"OK {e.Id} | {e.Name} | {e.Salary?.ToString() ?? "null"}");
}
errors.ForEach(x => Console.WriteLine("ERR " + x));
Rows 1 and 4 are returned, and the two broken rows are reported with their row number. Two things to know: BadDataFound is for malformed quoting, not for type errors, and a row that is missing a required value type (here JoinDate is a non-nullable DateTime) still fails conversion even with MissingFieldFound = null. Make the property nullable or give it a default if a short row should load.
Dynamic, records and reading field by field
If you do not want a class, GetRecords<dynamic>() returns objects whose properties are the header names. Every value is a string, so convert it yourself:
using (var reader = new StreamReader("employees.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
foreach (var r in csv.GetRecords<dynamic>())
Console.WriteLine($"{r.Id} - {r.Name} - '{r.Salary}'");
}
For full control, read the header and each row yourself and fetch fields by name:
using (var reader = new StreamReader("employees.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Read(); csv.ReadHeader();
while (csv.Read())
Console.WriteLine($"{csv.GetField<int>("Id")} {csv.GetField("Name")} {csv.GetField<decimal?>("Salary")}");
}
C# positional records work too. With public record EmployeeRec(int Id, string Name);, CsvHelper fills the constructor from the matching columns and ignores the others (set HeaderValidated = null and MissingFieldFound = null in the configuration as shown in Step 4 if the file has extra or missing columns):
using (var reader = new StreamReader("employees.csv"))
using (var csv = new CsvReader(reader, new CsvConfiguration(CultureInfo.InvariantCulture) { HeaderValidated = null, MissingFieldFound = null }))
{
foreach (var r in csv.GetRecords<EmployeeRec>()) Console.WriteLine(r);
}
public record EmployeeRec(int Id, string Name);
Read a large CSV file asynchronously
GetRecordsAsync<T>() returns an IAsyncEnumerable<T>. Rows are streamed, so a large file never sits in memory all at once, and the thread is free while the disk is read. This suits a web API or a background worker. For more on await in general, see Async await best practices.
using (var reader = new StreamReader("employees.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
await foreach (var e in csv.GetRecordsAsync<Employee>())
Console.WriteLine($"{e.Id} {e.Name}");
}
In an upload endpoint, pass the request stream into the StreamReader instead of a file path. To send a file back to a client, see Return and download a file from an ASP.NET Core Web API.
Write a CSV file
CsvWriter quotes values that need it. Dates use the culture’s format unless you set one, so pick an explicit format for files other systems read:
var list = new List<Employee> {
new() { Id = 1, Name = "Asha", Salary = 5200.5m, JoinDate = new DateTime(2022,3,14) },
new() { Id = 2, Name = "Smith, John", Salary = null, JoinDate = new DateTime(2020,7,30) } };
using (var writer = new StreamWriter("out.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.Context.TypeConverterOptionsCache.GetOptions<DateTime>().Formats = new[] { "yyyy-MM-dd" };
await csv.WriteRecordsAsync(list);
}
CsvHelper 34: the new API
Version 34 (November 2026) is a rewrite for speed. Everything lives in the CsvHelper namespace, readers are created with factory methods, settings are CsvReaderOptions, and your class is marked [CsvRecord] and partial so a source generator writes the mapping at compile time. ClassMap and the culture argument are gone (invariant culture is the default; set FormatProvider otherwise). This ran with dotnet add package CsvHelper --version 34.1.0:
using CsvHelper;
using (var reader = CsvReader.FromFile("employees.csv"))
{
foreach (var e in reader.GetRecords<Employee>())
Console.WriteLine($"{e.Id} | {e.Name} | {e.Salary?.ToString() ?? "null"} | {e.JoinDate:yyyy-MM-dd}");
}
// different header names, a European file, and an optional column
var options = new CsvReaderOptions { Separator = ';', FormatProvider = new System.Globalization.CultureInfo("de-DE") };
using (var reader = CsvReader.FromFile("people.csv", options))
{
foreach (var p in reader.GetRecords<Person>())
Console.WriteLine($"{p.Id} | {p.Name} | {p.Pay} | {p.Region}");
}
// no header: map by index
using (var reader = CsvReader.FromText("1,Asha,5200.50\n2,Ravi,4800\n", new CsvReaderOptions { HasHeader = false }))
{
foreach (var a in reader.GetRecords<Account>())
Console.WriteLine($"{a.Id} | {a.Name} | {a.Balance}");
}
// bad data: report malformed quoting, skip records that do not convert
// use it with: CsvReader.FromText(text, messy) or CsvReader.FromFile(path, messy)
var messy = new CsvReaderOptions
{
OnMalformedRecord = bad => Console.WriteLine($"malformed record {bad.RecordNumber}: {bad.Reason}"),
OnRecordError = err => { Console.WriteLine($"skipping record {err.RowNumber}: {err.Exception.Message}"); return true; },
};
// async and writing (list is the List<Employee> from the writing section)
await using (var reader = CsvReader.FromFile("employees.csv"))
{
await foreach (var e in reader.GetRecordsAsync<Employee>()) Console.WriteLine($"{e.Id} {e.Name}");
}
using (var writer = CsvWriter.ToFile("out.csv")) { writer.WriteRecords(list); }
[CsvRecord]
public partial class Employee
{
public int Id { get; set; }
public string Name { get; set; } = "";
public decimal? Salary { get; set; }
public DateTime JoinDate { get; set; }
}
[CsvRecord]
public partial class Person
{
[CsvColumn("emp_id")] public int Id { get; set; }
[CsvColumn("full_name")] public string Name { get; set; } = "";
[CsvColumn("pay")] public decimal Pay { get; set; }
[CsvColumn(Optional = true)] public string Region { get; set; } = "n/a";
}
[CsvRecord]
public partial class Account
{
[CsvColumn(Index = 0)] public int Id { get; set; }
[CsvColumn(Index = 1)] public string Name { get; set; } = "";
[CsvColumn(Index = 2)] public decimal Balance { get; set; }
}
Differences you will notice: the date column is written as ISO 8601 (2022-03-14T00:00:00.0000000) by default, a missing optional column keeps the property initializer and header names are matched ignoring case. Run with a file that had a text Id and a stray quote, the messy options skipped the bad records and reported them. Not tested in v34: dynamic records, non-UTF-8 encodings and the parallel readers.
What the output looks like
Running the 33.1.0 samples printed this (shortened where noted):
Common problems and fixes
HeaderValidationException: Header with name 'X' was not found: the header text does not match the property. Fix it withClassMapand.Name("..."), or setHeaderValidated = nullif the column is truly optional.TypeConverterExceptionon an empty value: an empty field cannot becomeintorDateTime. Useint?orDateTime?, or.Default(...)in a ClassMap.- Numbers read wrongly or throw: culture mismatch.
1.234,56needs a culture likede-DE; machine-made files usually needInvariantCulture. - The first header is not found although it looks right: a byte order mark or a trailing space. Open
StreamReaderwith the right encoding, and trim headers withPrepareHeaderForMatch = args => args.Header.Trim().ToLower()in the configuration (not tested here). MissingFieldException: a row has fewer fields than the header. SetMissingFieldFound = nullor log it, as in Step 4.- Semicolon or tab separated file reads as one column: set
Delimiter = ";"(or"\t") inCsvConfiguration. - Code from an old tutorial does not compile after upgrading: version 34 removed
CsvConfigurationandClassMap. Pin 33.1.0 or follow the migration guide.
Frequently asked questions
How do I read a CSV file in C# without a library?
You can use StreamReader with Split or TextFieldParser, but quoted fields with commas and line breaks make that fragile. See the general comparison in the linked post on reading CSV in .NET Core. CsvHelper removes that work.
Which CsvHelper version should I use?
Use 33.1.0 if you maintain existing code or follow older tutorials. Use 34.x for new projects on .NET 8 or later, after reading its migration guide, because the API is different and not source compatible.
How do I skip bad rows instead of failing the whole file?
In 33.x set ReadingExceptionOccurred to log the error and return false, and set MissingFieldFound and HeaderValidated to null as needed. In 34.x use OnRecordError and return true to skip the record.
Summary
To read a CSV file in C#, create a CsvReader with the right culture, map rows to a class with GetRecords<T>(), use ClassMap when headers differ, and handle missing and bad data through the configuration callbacks. Stream large files with GetRecordsAsync. Tested here: CsvHelper 33.1.0 reading, ClassMap, culture, no header, bad data, dynamic, records, async and writing, plus the 34.1.0 equivalents except dynamic. Not tested: very large files, non-UTF-8 encodings, fixed-width files, and the header trimming option.
Found this useful?
Bookmark this page and share it with your team. Get new .NET, cloud and database tutorials in your inbox.
