C# CSV Examples
C# Basic
C# Data Type
C# OOP
C# IO
C# Graphics & UI
C# Advanced
You can use the TextFieldParser
class in the Microsoft.VisualBasic.FileIO
namespace to read a CSV file and store its values to lists in C#. Here's an example:
using Microsoft.VisualBasic.FileIO; using System.Collections.Generic; string path = "data.csv"; List<string> column1 = new List<string>(); List<string> column2 = new List<string>(); using (TextFieldParser parser = new TextFieldParser(path)) { parser.TextFieldType = FieldType.Delimited; parser.SetDelimiters(","); while (!parser.EndOfData) { string[] fields = parser.ReadFields(); column1.Add(fields[0]); column2.Add(fields[1]); } }
In the above example, we first define the path of the CSV file and two lists to store its values. We then create a new TextFieldParser
object, set its field type to delimited, and set its delimiter to a comma. We then read each row of the CSV file using the ReadFields
method, and add its values to the corresponding lists.
You can use the CsvHelper
library to parse a CSV file with header, comment, and commas in C#. Here's an example:
using CsvHelper; using CsvHelper.Configuration; using System.Collections.Generic; using System.IO; string path = "data.csv"; List<string> column1 = new List<string>(); List<string> column2 = new List<string>(); using (var reader = new StreamReader(path)) using (var csv = new CsvReader(reader, new CsvConfiguration { HasHeaderRecord = true, Comment = '#' })) { csv.Configuration.Delimiter = ","; while (csv.Read()) { column1.Add(csv.GetField<string>("column1")); column2.Add(csv.GetField<string>("column2")); } }
In the above example, we first define the path of the CSV file and two lists to store its values. We then create a new StreamReader
object to read the CSV file, and pass it to a new CsvReader
object. We also configure the CsvConfiguration
object to indicate that the file has a header record and uses '#' as the comment character. We then set the delimiter to a comma, and read each row of the CSV file using the Read
method. Finally, we use the GetField
method to get the values of the 'column1' and 'column2' fields, and add them to the corresponding lists.
C# CSV file parsing with headers
CSV file parsing with headers involves reading a CSV file where the first row contains column headers. You can use libraries like CsvHelper or manually parse the file.
using System; using System.IO; using System.Linq; class Program { static void Main() { // Example using CsvHelper library using (var reader = new StreamReader("data.csv")) using (var csv = new CsvHelper.CsvReader(reader)) { var records = csv.GetRecords<dynamic>().ToList(); // Access data using column headers foreach (var record in records) { Console.WriteLine($"Name: {record.Name}, Age: {record.Age}"); } } } }
Reading CSV file with comments in C#
To read a CSV file with comments in C#, you can skip lines starting with a specific character (e.g., #
) using StreamReader
.
using System; using System.IO; class Program { static void Main() { using (var reader = new StreamReader("data.csv")) { while (!reader.EndOfStream) { var line = reader.ReadLine(); // Skip lines starting with # if (!line.StartsWith("#")) { // Parse and process the CSV data } } } } }
CSV parser for C# with header support
Libraries like CsvHelper provide built-in support for parsing CSV files with headers.
using System; using System.IO; using CsvHelper; class Program { static void Main() { using (var reader = new StreamReader("data.csv")) using (var csv = new CsvReader(reader)) { // Automatically maps to object properties using headers var records = csv.GetRecords<MyDataClass>().ToList(); foreach (var record in records) { Console.WriteLine($"Name: {record.Name}, Age: {record.Age}"); } } } } public class MyDataClass { public string Name { get; set; } public int Age { get; set; } }
C# CSV reader with customizable delimiters
You can use the TextFieldParser
class in C# for CSV parsing with customizable delimiters.
using System.IO; using Microsoft.VisualBasic.FileIO; class Program { static void Main() { using (var parser = new TextFieldParser("data.txt")) { parser.SetDelimiters(","); parser.HasFieldsEnclosedInQuotes = true; while (!parser.EndOfData) { var fields = parser.ReadFields(); // Process fields } } } }
Parsing CSV files with commas and quotes in C#
CSV files with commas and quotes can be handled using libraries like CsvHelper, which automatically handles quoted values.
using System; using System.IO; using CsvHelper; class Program { static void Main() { using (var reader = new StreamReader("data.csv")) using (var csv = new CsvReader(reader)) { var records = csv.GetRecords<MyDataClass>().ToList(); foreach (var record in records) { Console.WriteLine($"Name: {record.Name}, Age: {record.Age}"); } } } } public class MyDataClass { public string Name { get; set; } public int Age { get; set; } }
Ignoring comments while parsing CSV in C#
To ignore comments while parsing CSV in C#, you can use the TextFieldParser
class and skip lines starting with a comment character.
using System.IO; using Microsoft.VisualBasic.FileIO; class Program { static void Main() { using (var parser = new TextFieldParser("data.csv")) { parser.CommentTokens = new[] { "#" }; while (!parser.EndOfData) { var fields = parser.ReadFields(); // Process fields } } } }
C# CSV parsing library for complex formats
For complex CSV formats, libraries like CsvHelper offer advanced features such as custom type converters, record mapping, and more.
using System; using System.IO; using CsvHelper; class Program { static void Main() { using (var reader = new StreamReader("data.csv")) using (var csv = new CsvReader(reader)) { // Advanced features with CsvHelper csv.Configuration.RegisterClassMap<MyDataClassMap>(); var records = csv.GetRecords<MyDataClass>().ToList(); foreach (var record in records) { Console.WriteLine($"Name: {record.Name}, Age: {record.Age}"); } } } } public class MyDataClassMap : CsvHelper.Configuration.ClassMap<MyDataClass> { public MyDataClassMap() { Map(m => m.Name).Name("Full Name"); Map(m => m.Age).Name("Person Age"); } } public class MyDataClass { public string Name { get; set; } public int Age { get; set; } }
Reading CSV files with StreamReader in C#
Reading CSV files using StreamReader
involves manually splitting lines into fields based on the delimiter.
using System; using System.IO; class Program { static void Main() { using (var reader = new StreamReader("data.csv")) { while (!reader.EndOfStream) { var line = reader.ReadLine(); var fields = line.Split(','); // Process fields } } } }
Using TextFieldParser for CSV parsing in C#
The TextFieldParser
class simplifies CSV parsing in C# by handling delimiters, quoted values, and more.
using System.IO; using Microsoft.VisualBasic.FileIO; class Program { static void Main() { using (var parser = new TextFieldParser("data.csv")) { parser.TextFieldType = FieldType.Delimited; parser.SetDelimiters(","); while (!parser.EndOfData) { var fields = parser.ReadFields(); // Process fields } } } }
Handling escaped characters in CSV parsing with C#
Libraries like CsvHelper automatically handle escaped characters in CSV parsing. However, with manual parsing, you need to account for escaped characters.
using System; using System.IO; class Program { static void Main() { using (var reader = new StreamReader("data.csv")) { while (!reader.EndOfStream) { var line = reader.ReadLine(); // Custom logic to handle escaped characters var fields = CustomParseCsvLine(line); // Process fields } } } static string[] CustomParseCsvLine(string line) { // Custom logic to handle escaped characters and split fields // Example: Split by ',' while ignoring ',' within double quotes // ... return fields; } }