Skip to footer content
USING IRONXL

How to Read CSV Files in C# Using IronXL

Reading CSV files in C# .NET becomes trivial with IronXL -- a single method call loads comma-separated data into a structured workbook without any custom parsing code. This guide walks through every technique you need: basic loading, custom delimiters, DataTable conversion, cell-level access, error handling, and exporting to Excel format.

What Is the Easiest Way to Read CSV Files in .NET?

The simplest approach uses WorkBook.LoadCSV to import CSV data directly into a workbook structure. This single method handles parsing, delimiter detection, and data organization automatically -- no need to create a StreamReader or manually process each string line.

Install IronXL through the NuGet Package Manager Console in Visual Studio. Open your .NET project and run:

Install-Package IronXL
dotnet add package IronXL
Install-Package IronXL
dotnet add package IronXL
SHELL

Read CSV .NET: The Simplest C# Approach Using IronXL: Image 1 - Installation

using IronXL;

// Load CSV file into a workbook with one method call
WorkBook workbook = WorkBook.LoadCSV("sales_data.csv", fileFormat: ExcelFileFormat.XLSX, listDelimiter: ",");
// Access the default worksheet containing CSV data
WorkSheet sheet = workbook.DefaultWorkSheet;
// Display all rows and CSV columns
foreach (var row in sheet.Rows)
{
    foreach (var cell in row)
    {
        Console.Write(cell.Value + "\t");
    }
    Console.WriteLine();
}
using IronXL;

// Load CSV file into a workbook with one method call
WorkBook workbook = WorkBook.LoadCSV("sales_data.csv", fileFormat: ExcelFileFormat.XLSX, listDelimiter: ",");
// Access the default worksheet containing CSV data
WorkSheet sheet = workbook.DefaultWorkSheet;
// Display all rows and CSV columns
foreach (var row in sheet.Rows)
{
    foreach (var cell in row)
    {
        Console.Write(cell.Value + "\t");
    }
    Console.WriteLine();
}
$vbLabelText   $csharpLabel

Input

Read CSV .NET: The Simplest C# Approach Using IronXL: Image 2 - Sample CSV Input

Output

Read CSV .NET: The Simplest C# Approach Using IronXL: Image 3 - Console Output

The LoadCSV method accepts three parameters: the file path, the target Excel format for internal representation, and the delimiter character separating values. Once loaded, the CSV content becomes accessible through the DefaultWorkSheet property, which provides the primary worksheet containing all imported records.

The nested loop structure iterates through each Row in the worksheet, then through each Cell within that row. The Value property returns the cell content as an object, while the tab character creates readable column separation in the console output. This pattern works identically whether the source file contains 10 rows or large CSV files with thousands of records.

IronXL works across .NET Framework, .NET Core, and .NET 5+ without requiring Microsoft Office installation -- making it ideal for ASP.NET Core and .NET Core Web API projects. The library is available on NuGet and integrates cleanly into any project type. If you prefer to understand what a library handles for you, the next section covers what manual parsing involves.

How Does Manual CSV Parsing Compare to Using a Library?

Understanding the complexity that IronXL eliminates helps clarify its value. Manual CSV parsing requires handling multiple edge cases that appear simple but quickly become problematic in any project.

using System.IO;

// Manual approach -- requires extensive code for basic functionality
string path = "data.csv";
string[] lines = File.ReadAllLines(path);
foreach (string line in lines)
{
    // This breaks when CSV fields contain commas inside quotes
    string[] fields = line.Split(',');
    foreach (string field in fields)
    {
        Console.Write(field.Trim() + "\t");
    }
    Console.WriteLine();
}
using System.IO;

// Manual approach -- requires extensive code for basic functionality
string path = "data.csv";
string[] lines = File.ReadAllLines(path);
foreach (string line in lines)
{
    // This breaks when CSV fields contain commas inside quotes
    string[] fields = line.Split(',');
    foreach (string field in fields)
    {
        Console.Write(field.Trim() + "\t");
    }
    Console.WriteLine();
}
$vbLabelText   $csharpLabel

Input

Read CSV .NET: The Simplest C# Approach Using IronXL: Image 4 - CSV Input

Output

Read CSV .NET: The Simplest C# Approach Using IronXL: Image 5 - Manual CSV Parsing Output

The manual approach fails when CSV fields contain embedded commas within quoted strings -- a common scenario in address fields or descriptions. Reading files properly requires handling quoted fields, escaped quotes, multiline values, and varying encodings. Rolling your own parser means creating a StreamReader, implementing state-machine logic, and managing the entire read process yourself. That is considerable boilerplate for something that should be a one-liner.

The IronXL alternative handles all edge cases automatically:

using IronXL;

// IronXL approach -- handles all edge cases automatically
WorkBook workbook = WorkBook.LoadCSV("data.csv", fileFormat: ExcelFileFormat.XLSX, listDelimiter: ",");
var records = workbook.DefaultWorkSheet.Rows;
foreach (var row in records)
{
    foreach (var cell in row)
    {
        Console.Write(cell.Value + "\t");
    }
    Console.WriteLine();
}
using IronXL;

// IronXL approach -- handles all edge cases automatically
WorkBook workbook = WorkBook.LoadCSV("data.csv", fileFormat: ExcelFileFormat.XLSX, listDelimiter: ",");
var records = workbook.DefaultWorkSheet.Rows;
foreach (var row in records)
{
    foreach (var cell in row)
    {
        Console.Write(cell.Value + "\t");
    }
    Console.WriteLine();
}
$vbLabelText   $csharpLabel

The WorkBook class manages parsing complexity internally, letting you focus on working with the data rather than extracting it. You can read more about IronXL's full capabilities in the IronXL features overview.

How Do You Handle Different CSV Delimiters?

CSV files do not always use commas as separators. European system exports frequently use semicolons because commas appear in decimal numbers. Tab-separated values (TSV) and pipe-delimited files appear regularly in data exports from various applications and legacy systems.

using IronXL;

// Reading a semicolon-delimited file (common in European exports)
WorkBook euroData = WorkBook.LoadCSV("german_report.csv", fileFormat: ExcelFileFormat.XLSX, listDelimiter: ";");
// Reading a tab-separated file
WorkBook tsvData = WorkBook.LoadCSV("exported_data.tsv", fileFormat: ExcelFileFormat.XLSX, listDelimiter: "\t");
// Reading a pipe-delimited file
WorkBook pipeData = WorkBook.LoadCSV("legacy_system.csv", fileFormat: ExcelFileFormat.XLSX, listDelimiter: "|");
// Access data identically regardless of original delimiter
WorkSheet sheet = euroData.DefaultWorkSheet;
int rowsCount = sheet.RowCount;
Console.WriteLine($"Loaded {rowsCount} rows with {sheet.ColumnCount} CSV columns");
using IronXL;

// Reading a semicolon-delimited file (common in European exports)
WorkBook euroData = WorkBook.LoadCSV("german_report.csv", fileFormat: ExcelFileFormat.XLSX, listDelimiter: ";");
// Reading a tab-separated file
WorkBook tsvData = WorkBook.LoadCSV("exported_data.tsv", fileFormat: ExcelFileFormat.XLSX, listDelimiter: "\t");
// Reading a pipe-delimited file
WorkBook pipeData = WorkBook.LoadCSV("legacy_system.csv", fileFormat: ExcelFileFormat.XLSX, listDelimiter: "|");
// Access data identically regardless of original delimiter
WorkSheet sheet = euroData.DefaultWorkSheet;
int rowsCount = sheet.RowCount;
Console.WriteLine($"Loaded {rowsCount} rows with {sheet.ColumnCount} CSV columns");
$vbLabelText   $csharpLabel

The listDelimiter parameter in LoadCSV accepts any single character or escape sequence as the field separator. Tab characters use the \t escape sequence. After loading, the data structure remains consistent regardless of the original format, making it easy to process CSV files from multiple sources with varying delimiters. The default value for most CSV files is a comma, but this flexibility handles any variation a project encounters.

Input

Read CSV .NET: The Simplest C# Approach Using IronXL: Image 6 - Semicolon-delimited CSV File Input

Output

Read CSV .NET: The Simplest C# Approach Using IronXL: Image 7 - Semicolon-delimited Output

The RowCount and ColumnCount properties provide quick verification that the file loaded correctly -- especially useful when working with unfamiliar data sources or validating user uploads in an ASP.NET Core application.

Encoding Considerations

When reading files with non-ASCII characters, such as accented letters in French or German data, IronXL reads encoding from the file's byte order mark (BOM) automatically. For files without a BOM, you may need to verify the encoding at the source. Microsoft's documentation on file encoding provides a thorough reference for encoding types in .NET.

What Are the Best Methods for Converting CSV to DataTable?

Converting CSV data to a DataTable enables integration with database operations, data binding in UI applications, and LINQ queries. The ToDataTable method performs this conversion with a single call.

using IronXL;
using System.Data;

// Load CSV and convert to DataTable
WorkBook workbook = WorkBook.LoadCSV("customers.csv", ExcelFileFormat.XLSX, ",");
WorkSheet sheet = workbook.DefaultWorkSheet;
// Convert worksheet to DataTable -- true parameter uses CSV header as column names
DataTable dataTable = sheet.ToDataTable(true);
// DataTable is now ready for database operations, binding, or LINQ queries
Console.WriteLine($"DataTable created with {dataTable.Columns.Count} columns:");
foreach (DataColumn column in dataTable.Columns)
{
    // Property names from CSV header become column names
    Console.WriteLine($"  - {column.ColumnName}");
}
Console.WriteLine($"\nTotal records: {dataTable.Rows.Count}");
// Access data using standard DataTable syntax
foreach (DataRow row in dataTable.Rows)
{
    // Access by column index or name attribute
    string name = row["Name"].ToString();
    string email = row["Email"].ToString();
    Console.WriteLine($"Customer: {name}, Email: {email}");
}
using IronXL;
using System.Data;

// Load CSV and convert to DataTable
WorkBook workbook = WorkBook.LoadCSV("customers.csv", ExcelFileFormat.XLSX, ",");
WorkSheet sheet = workbook.DefaultWorkSheet;
// Convert worksheet to DataTable -- true parameter uses CSV header as column names
DataTable dataTable = sheet.ToDataTable(true);
// DataTable is now ready for database operations, binding, or LINQ queries
Console.WriteLine($"DataTable created with {dataTable.Columns.Count} columns:");
foreach (DataColumn column in dataTable.Columns)
{
    // Property names from CSV header become column names
    Console.WriteLine($"  - {column.ColumnName}");
}
Console.WriteLine($"\nTotal records: {dataTable.Rows.Count}");
// Access data using standard DataTable syntax
foreach (DataRow row in dataTable.Rows)
{
    // Access by column index or name attribute
    string name = row["Name"].ToString();
    string email = row["Email"].ToString();
    Console.WriteLine($"Customer: {name}, Email: {email}");
}
$vbLabelText   $csharpLabel

The boolean parameter in ToDataTable determines whether the first row should become column headers (true) or data (false). When set to true, the resulting DataTable's columns carry the header names from the CSV file, enabling intuitive data access using column names like row["Name"].

Using DataTable for Database and UI Integration

This conversion proves valuable for scenarios requiring database bulk inserts using SqlBulkCopy, populating DataGridView controls in Windows Forms applications, or performing complex data transformations with LINQ expressions. The DataTable format also integrates naturally with Entity Framework and other ORM tools in your .NET Core Web API project. You can read more about DataTable export patterns in the IronXL DataTable guide.

For additional patterns around working with tabular data in .NET, Microsoft's ADO.NET overview is an authoritative reference.

How Do You Convert CSV Files to Excel Format?

One of IronXL's standout capabilities is converting CSV data to proper Excel formats. This enables adding formulas, formatting, charts, and multiple worksheets to originally flat CSV data -- something you cannot achieve with CSV output alone.

using IronXL;

// Load CSV data from file path
string path = "quarterly_sales.csv";
WorkBook workbook = WorkBook.LoadCSV(path, ExcelFileFormat.XLSX, ",");
// Save as Excel XLSX format -- creates a new Excel file
workbook.SaveAs("quarterly_sales.xlsx");
// Alternative: Save as legacy XLS format for older Excel versions
workbook.SaveAs("quarterly_sales.xls");
Console.WriteLine("CSV successfully converted to Excel format");
using IronXL;

// Load CSV data from file path
string path = "quarterly_sales.csv";
WorkBook workbook = WorkBook.LoadCSV(path, ExcelFileFormat.XLSX, ",");
// Save as Excel XLSX format -- creates a new Excel file
workbook.SaveAs("quarterly_sales.xlsx");
// Alternative: Save as legacy XLS format for older Excel versions
workbook.SaveAs("quarterly_sales.xls");
Console.WriteLine("CSV successfully converted to Excel format");
$vbLabelText   $csharpLabel

The SaveAs method automatically determines the output format based on the file extension. XLSX creates modern Office Open XML files compatible with Excel 2007 and later, while XLS produces legacy Binary Interchange File Format documents for older applications.

Input

Read CSV .NET: The Simplest C# Approach Using IronXL: Image 8 - CSV Data

Output

Read CSV .NET: The Simplest C# Approach Using IronXL: Image 9 - Excel Output

Read CSV .NET: The Simplest C# Approach Using IronXL: Image 10 - CSV to Excel Output

This workflow proves particularly useful when CSV exports from databases or APIs need enhancement before distribution to users. After conversion, the Excel file can receive additional formatting, formulas, or be combined with other worksheets -- all programmatically through IronXL's editing capabilities. The process is fully scriptable, making it suitable for automated reporting pipelines or scheduled tasks.

How Do You Access Specific Cell Values in CSV Data?

Beyond iterating through all records, IronXL provides direct cell access using familiar Excel-style addressing. This enables targeted data extraction and type-safe value retrieval across different data types.

using IronXL;

WorkBook workbook = WorkBook.LoadCSV("inventory.csv", ExcelFileFormat.XLSX, ",");
WorkSheet sheet = workbook.DefaultWorkSheet;
// Access specific cells using Excel-style addresses by index
string productName = sheet["A2"].StringValue;
int quantity = sheet["B2"].IntValue;
decimal price = sheet["C2"].DecimalValue;
Console.WriteLine($"Product: {productName}");
Console.WriteLine($"Quantity: {quantity}");
Console.WriteLine($"Price: ${price:F2}");
// Access a range of cells -- return records from column A
var productRange = sheet["A2:A10"];
Console.WriteLine("\nAll products:");
foreach (var cell in productRange)
{
    Console.WriteLine($"  - {cell.StringValue}");
}
using IronXL;

WorkBook workbook = WorkBook.LoadCSV("inventory.csv", ExcelFileFormat.XLSX, ",");
WorkSheet sheet = workbook.DefaultWorkSheet;
// Access specific cells using Excel-style addresses by index
string productName = sheet["A2"].StringValue;
int quantity = sheet["B2"].IntValue;
decimal price = sheet["C2"].DecimalValue;
Console.WriteLine($"Product: {productName}");
Console.WriteLine($"Quantity: {quantity}");
Console.WriteLine($"Price: ${price:F2}");
// Access a range of cells -- return records from column A
var productRange = sheet["A2:A10"];
Console.WriteLine("\nAll products:");
foreach (var cell in productRange)
{
    Console.WriteLine($"  - {cell.StringValue}");
}
$vbLabelText   $csharpLabel

Cell addressing follows Excel conventions where letters represent CSV columns (A, B, C) and numbers represent row index positions (1, 2, 3). The Cell class provides type-specific accessors including StringValue, IntValue, DecimalValue, BoolValue, and DateTimeValue. These accessors handle parsing and conversion automatically, eliminating manual type casting compared to storing everything as string values.

Range selection using notation like A2:A10 returns a Range object that supports iteration, aggregate functions, and bulk operations. This proves valuable when extracting specific columns or rectangular data regions from large CSV files. For example, you might build a list of values from a specific column or write filtered data to another file. See the IronXL range guide for more patterns.

How Do You Handle Errors When Reading CSV Files?

Production applications require defensive code around file operations. CSV reading can fail for several reasons: the file does not exist, access is denied, the data is malformed, or memory is insufficient for very large files. Wrapping IronXL calls in try/catch blocks and validating paths before loading gives reliable behavior across environments.

using IronXL;
using System.IO;

string filePath = "customers.csv";
if (!File.Exists(filePath))
{
    Console.WriteLine($"File not found: {filePath}");
    return;
}
try
{
    WorkBook workbook = WorkBook.LoadCSV(filePath, ExcelFileFormat.XLSX, ",");
    WorkSheet sheet = workbook.DefaultWorkSheet;
    DataTable dataTable = sheet.ToDataTable(true);
    Console.WriteLine($"Loaded {dataTable.Rows.Count} records successfully.");
}
catch (IronXL.Exceptions.IronXLException ex)
{
    Console.WriteLine($"IronXL parsing error: {ex.Message}");
}
catch (IOException ex)
{
    Console.WriteLine($"File access error: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"Unexpected error: {ex.Message}");
}
using IronXL;
using System.IO;

string filePath = "customers.csv";
if (!File.Exists(filePath))
{
    Console.WriteLine($"File not found: {filePath}");
    return;
}
try
{
    WorkBook workbook = WorkBook.LoadCSV(filePath, ExcelFileFormat.XLSX, ",");
    WorkSheet sheet = workbook.DefaultWorkSheet;
    DataTable dataTable = sheet.ToDataTable(true);
    Console.WriteLine($"Loaded {dataTable.Rows.Count} records successfully.");
}
catch (IronXL.Exceptions.IronXLException ex)
{
    Console.WriteLine($"IronXL parsing error: {ex.Message}");
}
catch (IOException ex)
{
    Console.WriteLine($"File access error: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"Unexpected error: {ex.Message}");
}
$vbLabelText   $csharpLabel

Validation Patterns for CSV Data

Beyond catching exceptions, validating row and column counts after loading helps detect truncated files or unexpected schema changes. Checking sheet.RowCount against an expected minimum, or verifying that specific column headers exist in the first row, catches data issues early in the pipeline before they propagate downstream. Microsoft's exception handling guidance covers best practices for structured error handling in .NET.

For applications processing user-uploaded CSV files, always validate file size before loading, sanitize file names, and restrict the allowed content types at the upload endpoint. These precautions prevent resource exhaustion from oversized files and protect against path traversal attacks.

IronXL includes its own exception type IronXL.Exceptions.IronXLException for library-specific errors, which makes it straightforward to distinguish parsing failures from general input/output issues. You can find more details in the IronXL API reference.

How Do You Read Large CSV Files Without Memory Issues?

For files with hundreds of thousands of rows, loading the entire dataset into memory at once may be impractical. IronXL reads the whole file into a WorkBook object, which keeps all data in memory. For large-scale ETL (Extract, Transform, Load) scenarios, a practical strategy is to process the CSV in batches by splitting the source file before loading, or by streaming rows from a StreamReader and writing chunks to separate workbooks.

The IronXL documentation on reading Excel files covers performance considerations for large workloads. For CSV specifically, the CSV format's line-by-line structure means a simple File.ReadAllLines with manual batching gives predictable memory footprint when the dataset is too large for a single in-memory load.

Comparing IronXL with Alternative CSV Libraries

IronXL is not the only CSV library for .NET. CsvHelper is a widely used open-source alternative that specializes in streaming, record mapping, and attribute-based configuration. The key difference is scope: CsvHelper focuses exclusively on CSV, while IronXL handles the entire spreadsheet ecosystem -- reading, writing, and converting XLSX, XLS, CSV, and other formats through one unified API. If your application already uses IronXL for Excel operations, handling CSV with the same library avoids an extra dependency. If CSV is the only format you work with and you need streaming support, a streaming CSV library may serve you better.

IronXL vs. CsvHelper: Key Differences for CSV Reading in .NET
Feature IronXL CsvHelper
CSV reading Yes Yes
Excel (XLSX/XLS) support Yes No
Streaming large files In-memory only Yes (streaming)
Custom delimiters Yes (listDelimiter) Yes (configuration)
DataTable conversion Built-in (ToDataTable) Manual mapping
License Commercial Open source (MS-PL)

What Are Your Next Steps?

Reading CSV files in .NET requires minimal effort when using the right approach. IronXL's LoadCSV method handles parsing complexity automatically, supports various delimiters, provides immediate access to structured data, and converts to Excel or DataTable with single method calls. Whether you are building an ASP.NET Core application, a .NET Core Web API, or a console project, the library simplifies CSV processing from start to finish.

Explore more IronXL capabilities to extend what you have learned here:

Start a free trial to experience how IronXL simplifies reading CSV files in your .NET projects. For production deployment, licensing options include perpetual usage rights and one year of support.

Frequently Asked Questions

What is the simplest way to read CSV files in C#?

The simplest way to read CSV files in C# is by using IronXL, which provides a straightforward and efficient method to handle CSV data.

Can IronXL handle large CSV files efficiently?

Yes, IronXL is designed to handle large CSV files, making it suitable for processing extensive datasets without performance issues.

Is IronXL compatible with .NET applications?

IronXL is fully compatible with .NET applications, allowing developers to easily integrate CSV reading capabilities into their C# projects.

Does IronXL support reading CSV files with different delimiters?

IronXL supports reading CSV files with various delimiters, providing flexibility to handle files with different formats.

Can IronXL parse CSV files with headers?

Yes, IronXL can parse CSV files with headers, allowing you to easily access data by column names.

How does IronXL simplify CSV data manipulation?

IronXL simplifies CSV data manipulation by offering intuitive methods to read, edit, and write CSV data directly within C#.

Is there support for reading CSV files asynchronously in IronXL?

IronXL provides support for asynchronous operations, enabling you to read CSV files without blocking the main application thread.

Can IronXL convert CSV data to Excel format?

IronXL can convert CSV data to Excel format, allowing you to take advantage of Excel's features for data analysis and presentation.

Does IronXL have any dependencies for reading CSV files?

IronXL is a standalone library that does not require any external dependencies to read CSV files, simplifying the setup process in your projects.

Can IronXL be used to export data from CSV to other formats?

Yes, IronXL can export data from CSV to various formats, including Excel, providing versatility in data handling and reporting.

Jordi Bardia
Software Engineer
Jordi is most proficient in Python, C# and C++, when he isn’t leveraging his skills at Iron Software; he’s game programming. Sharing responsibilities for product testing, product development and research, Jordi adds immense value to continual product improvement. The varied experience keeps him challenged and engaged, and he ...
Read More

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me