Split CSV in C# while preserving commas inside quotes
How to split CSV lines in C# without breaking quoted fields: what string.Split gets wrong, how parsers change the data, and how to keep output usable.
Calling string.Split(',') on a CSV line works until a field contains a comma inside double quotes, such as a name written as "Smith, John". The split then cuts one field into two, every later column shifts, and the error is easy to miss. This review covers the common ways to split CSV in C# while ignoring commas inside quotes. For each one it explains what the method changes in the data, where it fails, and how to keep the output usable once it leaves your program.
Which approach suits your use?
For most real-world input, use a real CSV parser, either TextFieldParser, which ships with .NET, or an established CSV library. Avoid string.Split and regular expressions for this job. The benefit is correct handling of quoted delimiters and escaped quotes. The tradeoff is an extra API to learn or a package to add. A short hand-written state-machine parser is a reasonable middle ground when you control the input and want no dependencies. Plain string.Split is only appropriate when you know the data never contains quotes, embedded delimiters or line breaks inside fields, for example a numeric export your own code produces.
Why string.Split breaks quoted fields
In the common CSV convention, described in RFC 4180 and followed more or less strictly by many tools, a field containing a comma, a double quote or a line break is wrapped in double quotes. A literal quote inside such a field is written as two quotes. string.Split does not know this convention and splits on every comma. Take this input line:
1,"Smith, John","He said ""hi""",42
Splitting on every comma returns five pieces instead of four. The quotes are left in place, and the doubled quotes are not collapsed:
[0] 1
[1] "Smith
[2] John"
[3] "He said ""hi"""
[4] 42
A quote-aware parser returns the four intended fields:
[0] 1
[1] Smith, John
[2] He said "hi"
[3] 42
What splitting actually changes in the text
This is not a visual effect like mirrored glyphs or styled Unicode letters, and "split" here has nothing to do with reversing text. It changes the stored characters in exactly two ways. It removes the quotes that enclose a field, and it turns each doubled quote inside a quoted field into one quote. Every other character in a field should come through unchanged. If a method alters anything else, such as trimming spaces or dropping characters, that is a behavior to know about, not part of the CSV convention.
Character-by-character loops are safe for non-ASCII text in this case. The comma and the double quote are single ASCII characters. Neither the UTF-16 surrogate halves that make up emoji nor combining accent marks can equal either one. Multi-code-point emoji and accented letters are therefore copied into the field intact. Problems only appear later if you truncate, reverse or take substrings of fields by char index. That is a separate issue from splitting.
Option 1: TextFieldParser
TextFieldParser lives in the Microsoft.VisualBasic.FileIO namespace, but you can call it from C# like any other .NET class. It reads delimited text from a file or stream. When HasFieldsEnclosedInQuotes is true, it treats quoted commas as part of the field.
using Microsoft.VisualBasic.FileIO;
using var parser = new TextFieldParser("data.csv");
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
parser.HasFieldsEnclosedInQuotes = true;
parser.TrimWhiteSpace = false; // keep field content exactly as written
while (!parser.EndOfData)
{
var fields = parser.ReadFields();
// process fields
}
Three points to check before relying on it. First, TrimWhiteSpace defaults to true, which strips leading and trailing spaces from field values and quietly changes the data. Set it to false if spaces matter. Second, a line it cannot parse raises a MalformedLineException, so decide whether to skip, log or stop. Third, the parser reads from a stream and so can continue a quoted field onto the next line. Test that with a sample containing a quoted line break before you depend on it. Also confirm that the Microsoft.VisualBasic assembly is available for the .NET version you target.
Option 2: a small state-machine parser
If you want no dependency and your input is reasonably well formed, a single pass over the characters handles quoted commas and doubled quotes. The loop tracks whether it is inside quotes. It treats a comma as a field boundary only when it is outside quotes.
using System;
using System.Collections.Generic;
using System.Text;
public static class CsvSplitter
{
public static List<string> SplitLine(string line, char delimiter = ',')
{
var fields = new List<string>();
var field = new StringBuilder();
bool inQuotes = false;
for (int i = 0; i < line.Length; i++)
{
char c = line[i];
if (inQuotes)
{
if (c == '"')
{
if (i + 1 < line.Length && line[i + 1] == '"')
{
field.Append('"'); // escaped quote
i++;
}
else
{
inQuotes = false;
}
}
else
{
field.Append(c);
}
}
else if (c == '"')
{
inQuotes = true;
}
else if (c == delimiter)
{
fields.Add(field.ToString());
field.Clear();
}
else
{
field.Append(c);
}
}
if (inQuotes)
throw new FormatException("Unterminated quoted field.");
fields.Add(field.ToString());
return fields;
}
}
Tracing the earlier example line through this loop gives the four fields shown above. The code has known limits. It is lenient about a stray quote in the middle of an unquoted field and treats it as the start of a quoted section rather than rejecting the line. It reports an unclosed quote as an error instead of guessing. It also only sees one line at a time, so a field with a quoted line break needs the whole record passed in. One way to extend it is to append the next line when an unterminated quote is detected and try again.
Option 3: a regular expression with lookahead
A common answer to this problem is to split only on commas followed by an even number of quotes. That means splitting only on commas that sit outside quoted sections:
using System.Text.RegularExpressions;
var fields = Regex.Split(line, @",(?=(?:[^""]*""[^""]*"")*[^""]*$)");
On the example line, this produces the correct four boundaries. However, the second and third fields still carry their enclosing quotes, and the doubled quotes remain doubled. You must strip and unescape them yourself. The pattern also rescans the rest of the line at every comma, gives wrong results on malformed quoting without any error, and cannot handle quoted line breaks when reading line by line. It suits quick scripts on trusted data, not production imports.
Option 4: a dedicated CSV library
Third-party packages such as CsvHelper are widely used in C# projects for reading and writing CSV. They can also map records onto typed classes. The cost is an external dependency and its configuration options. Before you rely on a library's handling of quotes, escaping, trimming and line breaks, check its documentation for the version you install. This review did not test any specific library.
How the options compare
| Approach | Ignores commas in quotes | Unescapes doubled quotes | Quoted line breaks | Dependency |
| string.Split | No | No | No | None |
| Regex lookahead | Yes, on well-formed input | No, needs post-processing | No when reading line by line | None |
| State-machine parser above | Yes | Yes | Only if given the full record | None |
| TextFieldParser | Yes, with HasFieldsEnclosedInQuotes | Yes | Verify with your own sample | Included with .NET |
| CSV library | Generally yes; confirm in its documentation | Confirm in its documentation | Confirm in its documentation | External package |
Will the result stay usable after copying or sharing?
Parsed fields are plain strings, so copying them elsewhere carries no hidden formatting. The risk comes when you write data back out as CSV. A field that contains the delimiter, a quote or a line break must be quoted again, with its inner quotes doubled. Otherwise the next reader hits the same problem you just solved. A minimal escape function looks like this:
static string EscapeField(string value, char delimiter = ',')
{
if (value.IndexOfAny(new[] { delimiter, '"', '\r', '\n' }) < 0)
return value;
return "\"" + value.Replace("\"", "\"\"") + "\"";
}
Other compatibility limits sit outside the parsing step itself. Some spreadsheet setups expect a semicolon rather than a comma, depending on regional settings. Text encoding and the presence or absence of a byte order mark can affect how non-ASCII characters appear when a file is opened. Spreadsheet applications may also convert values that look like numbers or dates, such as codes with leading zeros. None of this is fixed by splitting correctly. Test the actual destination with a file containing these cases rather than assuming that one good result applies everywhere.
For accessibility, raw CSV is plain text, and quote-aware splitting does not change reading order. Delimited text is still hard to follow when read aloud, though. When people rather than programs will use the data, present the parsed fields as a proper table with column headers. Keep the CSV file as the machine-readable copy.
Gaps and how to check your own case
No performance measurements, library version details or destination-specific test results were available for this review. The behavior described comes from the documented CSV convention, the .NET APIs named above and the worked example. Before choosing a method, run your candidate against a small set of test lines like these:
- A quoted field containing a comma
- A quoted field containing doubled quotes
- A quoted field containing a line break
- An empty field and an empty quoted field next to each other
- Leading and trailing spaces inside and outside quotes
- An unclosed quote, to see whether the method errors or silently misreads
- Non-ASCII text, including accented letters and emoji