CSV files are commonly used to exchange data between applications, import records into databases, generate reports, and transfer information between different systems. Their simple structure makes them easy to create and read. However, processing large CSV files can become a serious performance problem when an application tries to load the entire file into memory.

Consider an application that imports customer transactions from a CSV file containing several million records. A straightforward implementation using File.ReadAllLines() or File.ReadAllText() may work with smaller files, but it can consume a significant amount of memory as the file grows. Converting all rows into a List of objects creates additional memory allocations and can eventually cause an OutOfMemoryException.

The problem is not necessarily the CSV file itself. It is how the application reads and processes the data.

.NET provides several ways to process files incrementally. By using StreamReader, asynchronous reading, and batch processing, developers can process large CSV files without keeping the complete dataset in memory.

In this article, we will explore how to read huge CSV files efficiently in .NET, process records in smaller batches, handle invalid data, and build a reliable CSV import process suitable for production applications.

Why Loading an Entire CSV File Into Memory Is a Problem

Many developers initially use File.ReadAllLines() because it provides a simple way to access file contents.

For example:

C#
string[] lines = File.ReadAllLines("transactions.csv");

foreach (string line in lines)
{
    Console.WriteLine(line);
}

This approach reads every line and stores it in a string array. If the file contains millions of records, the application must allocate memory for the complete file before processing begins.

The problem becomes bigger when developers convert those strings into objects.

C#
var transactions = File.ReadAllLines("transactions.csv")
    .Skip(1)
    .Select(line =>
    {
        string[] values = line.Split(',');

        return new Transaction
        {
            Id = int.Parse(values[0]),
            CustomerName = values[1],
            Amount = decimal.Parse(values[2])
        };
    })
    .ToList();

This implementation creates several allocations:

  • An array containing all file lines.
  • Individual string objects for the records.
  • Additional arrays created by Split().
  • Transaction objects stored in a List.
  • Temporary objects created during conversion.

When the dataset becomes large, these allocations increase garbage collection activity and memory pressure.

A better approach is to read one record at a time, process it, and move to the next record.

Understanding Streaming in .NET

Streaming means reading data incrementally instead of loading the complete file into memory.

.NET provides the StreamReader class for reading text files sequentially. It maintains a buffer and reads additional data as needed.

Consider the following example:

C#
using var reader = new StreamReader("transactions.csv");

string? line;

while ((line = reader.ReadLine()) != null)
{
    Console.WriteLine(line);
}

Unlike File.ReadAllLines(), this implementation does not create an array containing every line.

The application reads one line, processes it, and continues until the end of the file.

This approach is useful for large CSV files because memory usage depends primarily on the current line and processing requirements rather than the complete file size.

However, there is another important consideration. CSV is not always as simple as splitting a line using commas.

For example:

Code
Id,CustomerName,Amount
101,Rahul,1500
102,"Priya, Sharma",2500

The second customer name contains a comma inside quotation marks. Using Split(',') incorrectly separates that value into two fields.

CSV also supports escaped quotation marks and quoted fields containing line breaks. Therefore, production applications should use a proper CSV parser instead of implementing CSV parsing manually.

Using CsvHelper to Read Large CSV Files

CsvHelper is a popular .NET library for reading and writing CSV data. It supports typed records, configurable parsing, validation, and asynchronous record enumeration.

First, create a console application:

Bash
dotnet new console -n LargeCsvProcessor
cd LargeCsvProcessor

Install the package:

Bash
dotnet add package CsvHelper

Creating a Transaction Model

Suppose the CSV file contains transaction information.

Create a model:

C#
public class Transaction
{
    public int Id { get; set; }

    public string CustomerName { get; set; } = string.Empty;

    public decimal Amount { get; set; }
}

This model represents each CSV record in the application.

Reading Records Asynchronously

The following example reads records incrementally using CsvHelper.

C#
using CsvHelper;
using CsvHelper.Configuration;
using System.Globalization;

public static async Task ReadTransactionsAsync(
    string filePath,
    CancellationToken cancellationToken = default)
{
    var configuration = new CsvConfiguration(
        CultureInfo.InvariantCulture)
    {
        HasHeaderRecord = true,
        Delimiter = ",",
        IgnoreBlankLines = true
    };

    using var reader = new StreamReader(filePath);

    using var csv = new CsvReader(reader, configuration);

    long processedCount = 0;

    await foreach (Transaction transaction in
        csv.GetRecordsAsync<Transaction>(cancellationToken))
    {
        cancellationToken.ThrowIfCancellationRequested();

        Console.WriteLine(
            $"{transaction.Id} - " +
            $"{transaction.CustomerName} - " +
            $"{transaction.Amount}");

        processedCount++;
    }

    Console.WriteLine(
        $"Total processed records: {processedCount}");
}

The important part is GetRecordsAsync(). It returns an asynchronous stream of records instead of requiring the application to create a List containing the complete dataset.

The await foreach statement retrieves records incrementally. Each transaction can be processed before the next record is requested.

The application does not need to keep previously processed transactions in memory.

Using CultureInfo.InvariantCulture is also important when processing files exchanged between different systems. It helps ensure that numeric values and decimal separators are interpreted consistently rather than depending on the machine's regional settings.

Processing Large CSV Files in Batches

Reading one record at a time is useful, but many production operations work better with batches.

For example, when importing CSV data into SQL Server or PostgreSQL, inserting one record at a time can introduce unnecessary database communication overhead.

Instead, the application can collect a limited number of records, insert them together, and clear the batch before processing additional records.

Implementing Batch Processing

C#
public static async Task ProcessTransactionsInBatchesAsync(
    string filePath,
    CancellationToken cancellationToken = default)
{
    const int batchSize = 1000;

    var configuration = new CsvConfiguration(
        CultureInfo.InvariantCulture)
    {
        HasHeaderRecord = true
    };

    using var reader = new StreamReader(filePath);

    using var csv = new CsvReader(reader, configuration);

    var batch = new List<Transaction>(batchSize);

    long totalProcessed = 0;

    await foreach (Transaction transaction in
        csv.GetRecordsAsync<Transaction>(cancellationToken))
    {
        batch.Add(transaction);

        if (batch.Count >= batchSize)
        {
            await SaveBatchAsync(batch, cancellationToken);

            totalProcessed += batch.Count;

            batch.Clear();
        }
    }

    if (batch.Count > 0)
    {
        await SaveBatchAsync(batch, cancellationToken);

        totalProcessed += batch.Count;
    }

    Console.WriteLine(
        $"Successfully processed {totalProcessed} records.");
}

private static async Task SaveBatchAsync(
    List<Transaction> transactions,
    CancellationToken cancellationToken)
{
    // Insert the current batch into the database.
    // Replace this implementation with your database operation.

    await Task.Delay(10, cancellationToken);
}

In this implementation, the application processes 1,000 transactions at a time.

Once the batch reaches its configured size, SaveBatchAsync() processes the records. The list is then cleared and reused for the next batch.

The final condition is equally important. A CSV file may contain a number of records that is not evenly divisible by the batch size. Without the final batch check, the remaining records would never be processed.

In a real application, SaveBatchAsync() could use a database bulk-copy operation, a parameterized batch insert, or another suitable persistence mechanism.

One important consideration is that the database operation should complete successfully before clearing the batch. Otherwise, a failed database operation could result in lost records.

Reading CSV Files Using FileStream and StreamReader

For applications that need more control over file access, developers can combine FileStream and StreamReader.

C#
using var fileStream = new FileStream(
    "transactions.csv",
    FileMode.Open,
    FileAccess.Read,
    FileShare.Read,
    bufferSize: 64 * 1024,
    options: FileOptions.SequentialScan);

using var reader = new StreamReader(fileStream);

string? line;

while ((line = await reader.ReadLineAsync(cancellationToken))
       != null)
{
    Console.WriteLine(line);
}

This implementation uses a 64 KB buffer and SequentialScan to indicate that the application reads the file sequentially.

This can be useful when processing large files from local storage.

However, increasing the buffer size does not automatically improve performance. The appropriate buffer depends on the storage system, file characteristics, and workload. It should be measured rather than selected arbitrarily.

For CSV files containing quoted fields, continue using a CSV parser instead of treating each physical line as an independent record.

Handling Invalid Records Without Stopping the Import

Large CSV files frequently contain invalid records. Examples include missing customer names, incorrect decimal values, unexpected column counts, and malformed quotation marks.

A production import process should have a clear strategy for handling these problems.

Not every invalid record should cause the entire import to fail.

For example, developers can configure CsvHelper to report parsing errors and skip invalid records when the import requirements permit it.

C#
var configuration = new CsvConfiguration(
    CultureInfo.InvariantCulture)
{
    HasHeaderRecord = true,

    BadDataFound = context =>
    {
        Console.WriteLine(
            $"Invalid CSV data: {context.RawRecord}");
    },

    MissingFieldFound = null
};

This configuration provides a basic way to customize error handling.

However, reporting malformed CSV syntax does not automatically guarantee that every invalid record will be skipped safely. Applications should explicitly handle CsvHelper exceptions and validate successfully parsed records before saving them.

For example:

C#
if (transaction.Id <= 0)
{
    Console.WriteLine("Invalid transaction ID.");
    continue;
}

if (transaction.Amount < 0)
{
    Console.WriteLine("Invalid transaction amount.");
    continue;
}

For production systems, maintain an error report containing the record number, validation reason, and relevant information needed for investigation. Avoid logging sensitive customer information unnecessarily.

Comparing Different CSV Reading Approaches

Approach

Memory Usage

Advantages

Limitations

File.ReadAllText()

High

Simple for small files

Loads the complete file

File.ReadAllLines()

High

Easy line-based processing

Stores every line

StreamReader

Low

Reads incrementally

Requires parsing logic

StreamReader with CsvHelper

Low

Handles CSV formatting and streaming

Requires an additional package

Batch processing

Controlled

Suitable for database imports

Requires batch management

For large CSV files, StreamReader with CsvHelper and controlled batch processing is a practical combination.

Best Practices for Production Applications

Choose an Appropriate Batch Size

Avoid using an unnecessarily large batch size. More records in each batch mean more objects and temporary arrays may remain in memory.

Start with a manageable value, such as 1,000 records, and adjust it according to record size, database performance, and memory usage.

Validate Data Before Database Insertion

Do not assume that successfully parsed CSV records contain valid business data.

Validate required fields, numeric ranges, identifiers, and business rules before inserting records.

Use Cancellation Tokens

Large imports may take considerable time. Pass CancellationToken through file reading and database operations so that an operation can stop when requested.

Avoid Excessive Parallel Processing

Reading a CSV file sequentially is often sufficient. If parallel processing is necessary, use a bounded processing queue so that incoming records cannot accumulate without limits.

Keep Error Handling Separate From Processing

Maintain a separate error-handling mechanism for invalid records. This makes it easier to investigate failed imports without stopping the complete process unnecessarily.

Monitor Memory and Processing Performance

Monitor managed heap usage, garbage collection, processing duration, and database insertion performance.

Do not rely only on file size to estimate memory requirements. Long text fields, object allocations, and batch sizes can significantly affect actual memory consumption.

Make Database Imports Idempotent

If an import fails halfway through, the application may need to restart it.

Use transaction boundaries, unique business identifiers, or an import tracking mechanism to prevent duplicate records when processing the same file again.

Common Mistakes to Avoid

Mistake

Impact

Better Approach

Using File.ReadAllLines()

High memory consumption

Use StreamReader

Using Split(',')

Incorrect parsing of quoted fields

Use CsvHelper

Converting all records to a List

Retains the complete dataset

Use asynchronous enumeration

Ignoring the final batch

Records remain unprocessed

Process remaining records

Using very large batches

Increased memory pressure

Tune batch size

Ignoring invalid records

Import failures or incorrect data

Validate and log errors

Running unlimited parallel tasks

Uncontrolled memory growth

Use bounded concurrency

Clearing a batch before saving succeeds

Potential data loss

Clear only after successful processing

Summary

Reading huge CSV files in .NET does not require loading the complete file into memory. By using StreamReader, CsvHelper, asynchronous enumeration, and batch processing, developers can build efficient file-processing applications that handle large datasets with controlled memory usage.

For simple sequential processing, StreamReader is a good starting point. When CSV files contain quoted fields, escaped characters, and complex values, CsvHelper provides a more reliable parsing solution.

For database imports and other large-scale operations, batch processing provides better control over memory consumption and data persistence.

The most important principle is to read only what is needed, process records incrementally, release processed data, and avoid allowing incoming records to accumulate without limits. These practices make CSV processing more reliable, maintainable, and suitable for production .NET applications.