Home
C#
CSV Method Example
This page was last reviewed on Dec 8, 2023.
Dot Net Perls
CSV. A comma-separated values file stores data—it separates each unit with a comma character. In C# we can use built-in methods like Split to parse CSV files.
For maximum performance, a method that handles each byte in a for-loop would be best. But for more clarity, calling the Split method on each line from the file is better.
TextFieldParser
JSON
First example. To run this example, be sure to change the path specified in the Main method to a CSV file that exists. The CSV file will be read and parsed.
String Split
Step 1 We specify a string containing the path of the CSV file (relative to the home directory) we want to parse.
Step 2 With File.ReadLines, we handle each line individually, without loading the entire file into an array at once.
File.ReadLines
Step 3 We call Split to separate the line on all the comma characters. This does not handle escaped characters.
Step 4 With a foreach-loop, we print out each individual field within the line of the CSV file.
foreach
using System; using System.IO; class Program { static void HandleFile(string path) { // Step 2: read each line individually with ReadLines. foreach (string line in File.ReadLines(path)) { // Step 3: split the line on a comma. string[] parts = line.Split(','); // Step 4: loop over the lines and do something with them. foreach (string value in parts) { Console.WriteLine("PART: {0}", value); } } } static void Main() { // Step 1: specify the CSV file path. HandleFile("programs/example.txt"); } }
PART: Field1 PART: Field2 PART: Field3 PART: Field4 PART: 100 PART: 200 PART: 300
Summary. There are many ways to handle CSV files in C# programs. With a File.ReadLines and Split, we can handle many files without using any external code.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 8, 2023 (new example).
Home
Changes
© 2007-2024 Sam Allen.