Skip to footer content
USING IRONXL

Read CSV .NET: The Simplest C# Approach Using IronXL

Read CSV .NET: The Simplest C# Approach Using IronXL

Reading and writing CSV files in .NET applications becomes remarkably straightforward with the right library. Instead of writing custom parsing logic to handle delimiters, quoted fields, and various data types, developers can load CSV data with a single method call and immediately access it as structured spreadsheet data in a table format.

IronXL transforms CSV processing by treating comma-separated files as Excel workbooks. This .NET library eliminates the complexity of manual string parsing while providing powerful features like DataTable conversion, cell-level access, and seamless Excel format output. The library 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.

This guide demonstrates practical techniques for reading CSV files, handling custom delimiters, converting records to DataTables, and writing CSV files to Excel formats—all with minimal code. Each code example includes detailed explanations to help you understand how the system works.

Introduction to Working with CSV Files

CSV files (Comma Separated Values) are a staple in data exchange and storage, thanks to their simplicity and broad compatibility. Whether you’re importing data into a database, exporting reports, or integrating with third-party systems, CSV files provide a lightweight and flexible format for handling tabular data. In .NET, working with CSV files is a common task—developers often need to parse, read, and write CSV data as part of business logic, reporting, or data migration workflows.

The .NET system offers several ways to process CSV files, from basic string and file operations to robust libraries like CsvHelper. Proper parsing is essential, as even a simple comma can introduce complexity when it appears inside quoted fields or as part of the data itself. By leveraging the right .NET tools and understanding the nuances of CSV parsing, developers can ensure data integrity and streamline data processing in their applications.

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

The simplest approach uses the WorkBook.LoadCSV method 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 new 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.Excel

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

using IronXL;
using System;

class Program
{
    static void Main(string[] args)
    {
        // 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;
using System;

class Program
{
    static void Main(string[] args)
    {
        // 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();
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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

Alternatively, you can read a CSV file using the CsvHelper library, which is popular for handling CSV operations in .NET. To read a CSV file using CsvHelper, create a StreamReader and then a new CsvReader instance, often assigned to a variable like var csv or var reader:

using (var reader = new StreamReader("sales_data.csv"))
using (var csv = new CsvHelper.CsvReader(reader, System.Globalization.CultureInfo.InvariantCulture))
{
    var records = csv.GetRecords<dynamic>().ToList();
    // Process records as needed
}
using (var reader = new StreamReader("sales_data.csv"))
using (var csv = new CsvHelper.CsvReader(reader, System.Globalization.CultureInfo.InvariantCulture))
{
    var records = csv.GetRecords<dynamic>().ToList();
    // Process records as needed
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

You can also write to a CSV file using CsvHelper by creating a StreamWriter and a CsvWriter instance.

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 handles large CSV files with thousands of records in memory.

How Does Manual CSV Parsing Compare to Using a Library?

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

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        // 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;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        // 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();
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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 and writing CSV files properly requires handling quoted fields, escaped quotes, multiline values, and varying encodings. Using the CsvHelper library or similar CSV Helper packages adds dependencies, while rolling your own parser means creating a new StreamReader, implementing a var reader pattern, and managing the entire file read process yourself.

using IronXL;
using System;

class Program
{
    static void Main(string[] args)
    {
        // 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;
using System;

class Program
{
    static void Main(string[] args)
    {
        // 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();
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The IronXL version accomplishes the same task while properly handling quoted CSV fields, special characters, and encoding variations. The WorkBook class manages parsing complexity internally, allowing developers to focus on working with the data rather than extracting it. Unlike approaches requiring a new CsvReader instance or CsvHelper package configuration, IronXL needs no additional setup—just load and use.

How Can Different CSV Delimiters Be Handled?

CSV files don't always use commas as separators. European system exports frequently use semicolons due to comma usage in decimal numbers, while tab-separated values (TSV) and pipe-delimited files appear regularly in data exports from various applications.

using IronXL;
using System;

class Program
{
    static void Main(string[] args)
    {
        // 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;
using System;

class Program
{
    static void Main(string[] args)
    {
        // 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");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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 your 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 class properties provide quick verification that the file loaded correctly, which proves especially useful when working with unfamiliar data sources or validating user uploads in an ASP.NET Core application.

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;
using System.Data;

class Program
{
    static void Main(string[] args)
    {
        // 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 file 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;
using System.Data;

class Program
{
    static void Main(string[] args)
    {
        // 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 file 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}");
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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 property names from the CSV file header row, enabling intuitive data access using column names like row["Name"].

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.

Can CSV Files Be Converted 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 writing CSV files alone.

using IronXL;
using System;

class Program
{
    static void Main(string[] args)
    {
        // Load CSV data from file path
        string path = "quarterly_sales.csv";
        WorkBook workbook = WorkBook.LoadCSV(path, ExcelFileFormat.XLSX, ",");
        // Save as Excel XLSX format - create 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;
using System;

class Program
{
    static void Main(string[] args)
    {
        // Load CSV data from file path
        string path = "quarterly_sales.csv";
        WorkBook workbook = WorkBook.LoadCSV(path, ExcelFileFormat.XLSX, ",");
        // Save as Excel XLSX format - create 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");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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 a user. After conversion, the Excel file can receive additional formatting, formulas, or be combined with other worksheets—all programmatically through IronXL's comprehensive editing capabilities. Unlike approaches using a var writer with a new StreamWriter instance for writing CSV files, IronXL handles the entire file conversion seamlessly.

How Are Specific Cell Values Accessed 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;
using System;

// Example class to demonstrate structured data access
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        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;
using System;

// Example class to demonstrate structured data access
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        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}");
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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 and reducing memory overhead 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 create a new List of values from a specific column or write filtered data to another file.

Error Handling in CSV File Operations

Robust error handling is essential when working with CSV files in .NET applications. Reading and writing CSV files can lead to a variety of issues, such as missing files, malformed data, or unexpected parsing errors. To manage these scenarios, it’s best practice to wrap file and data operations in try-catch blocks, allowing your application to gracefully handle exceptions and provide meaningful feedback.

Conclusion

Reading CSV files in .NET requires minimal effort when using the right approach. IronXL's LoadCSV method handles parsing complexity automatically, supporting various delimiters and providing immediate access to structured data through familiar spreadsheet concepts. Whether you're building an ASP.NET Core application, a .NET Core Web API, or a console project, this library streamlines CSV processing.

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

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 efficiently 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 leverage Excel's advanced 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