System.OutOfMemoryException from CsvParser.FillBuffer
Describe the bug Trying to read a very large file that is not correctly formatted as CSV may result in an out of memory exception when calling Read().
To Reproduce
// create a large file using cmd.exe
// fsutil file createnew 1gb.tst 1073741824
const string filePath = @"C:\1gb.tst";
try
{
using (var stream = File.OpenRead(filePath))
{
using (var csvReader = new CsvReader(new StreamReader(stream), CultureInfo.InvariantCulture))
{
csvReader.Read();
}
}
}
catch (CsvHelperException)
{
// pass
}
catch (OutOfMemoryException)
{
// fail
}
Expected behavior CsvHelper does not use an excessive amount of memory and a more appropriate exception such as BadDataException is thrown.
After some investigation, I found that the RFC 4180 CSV specification does not explicitly forbid null characters (0x00) in CSV files. The RFC is silent on most control characters, only specifying that line breaks should be CRLF, and that fields containing CR, LF, or commas should be enclosed in double quotes (see RFC 4180, Section 2).
As a result, a file filled with null bytes is not technically invalid by the spec, and CsvHelper might interpret it as a CSV with one row and one column containing an empty value.
From my perspective, I see two possible directions to address this issue (though there may be other or better approaches):
- Restrict memory usage during parsing to avoid an OutOfMemoryException and instead throw a more appropriate exception if an unexpected file structure is encountered. However, this could be complex to implement and maintain.
- Ignore or reject all control characters except LF and CR during parsing, which aligns with the practical expectations of CSV as a text format and improves robustness against malformed or non-text files. That said, this could impact users who expect those control characters to be present. To avoid breaking existing behavior, this could be implemented as a configurable parser option, defaulting to the current behavior.
I'm new to the project, so these are just some initial thoughts—I’m definitely open to other ideas or feedback from the community. Looking forward to the discussion!